Unterminated entity reference in PHP
When SimpleXMLElement::addChild() throws a warning about an "unterminated entity reference," the root cause is almost always how data from the database is being injected into XML attributes or text nodes without proper sanitization. The error message specifically points to Coke.jpg as the problematic value. This indicates that the string stored in your $row[imag_url] column contains special charactersâspecifically an ampersand (&)âthat have not been escaped before being written into the XML structure.
In the provided code snippet, the line triggering the error is:
$product->addchild('image_url', "$row[imag_url]");
The PHP DOM and SimpleXML libraries treat strings containing unescaped special characters as invalid XML. If your database contains a URL like http://example.com/Co&ke.jpg, the parser reads the ampersand as the start of an entity reference (like & or <). Since the string ends with just ke.jpg, the parser expects to find a closing semicolon and a defined entity name, which never arrives. Consequently, it throws the "unterminated entity reference" exception.
The immediate fix involves escaping the data before passing it to addChild(). You can use htmlspecialchars() with the flag ENT_XML1 or simply ENT_QUOTES combined with an appropriate encoding (usually UTF-8). Here is how the corrected line should look:
$product->addChild('image_url', htmlspecialchars($row[imag_url], ENT_XML1 | ENT_COMPAT, 'UTF-8'));
This function converts special characters into their corresponding HTML/XML entity equivalents (e.g., converting & to &). It ensures that the XML parser sees a literal ampersand rather than the start of an incomplete tag.
However, relying solely on addchild() with string interpolation for all fields introduces significant security risks and fragility. The code provided mixes direct concatenation ("$row[...]") with method calls. While the immediate error is about XML validity, this pattern invites Cross-Site Scripting (XSS) vulnerabilities if the database contains malicious scripts. For example, if $row[product_name] contains <script>alert('xss')</script>, that script would execute in any browser rendering your RSS feed.
A more robust approach is to use SimpleXMLElement::addChild() with explicit escaping for every single field, or better yet, leverage XML serialization libraries designed for this purpose. In modern PHP development (version 5.2+), you should consider using the DOMDocument class or the built-in xml_encode function if available in your specific framework, though SimpleXML remains popular for its brevity.
If you are maintaining legacy code that uses mysql_* functions, you are already operating on deprecated APIs that have been removed as of PHP 7.1. Migrating to mysqli or PDO is not just a recommendation; it is a requirement for security and support. The mysql_fetch_array() function returns data in a way that assumes no validation has occurred, placing the entire burden of sanitization on your application logic.
There is also a subtle but important distinction between adding elements as text versus attributes. In the code, image_url is added as a child element (implied by the context of RSS feeds usually having <link> tags), but if you intended it to be an attribute (e.g., <item image_url="..." />), the syntax changes. The error occurs regardless because the content itself is malformed XML until escaped.
For production environments where data integrity is paramount, never trust the database blindly. Even if your schema enforces strict types, user-generated content or imported CSVs often contain edge cases like , <, >, or quotes. Always apply output encoding at the point of insertion into the XML document. If you are building a larger application, consider using a framework like Laravel, which handles these escaping concerns automatically when binding data to views or generating responses.
Finally, ensure that your final asXML() output is served with the correct character set header. Even if you escape the content correctly, serving the file as text/xml without declaring the encoding can lead to further parsing issues in client applications like RSS readers. Always include:
header('Content-Type: text/xml; charset=UTF-8');
This ensures that clients interpret the entity references correctly and renders your feed consistently across different devices.