PHP - String could not be parsed as XML
When attempting to fetch and parse XML data in PHP, encountering the SimpleXMLElement error "String could not be parsed as XML" is a common hurdle. The immediate reaction is often to check for typos or encoding issues, but in many cases, the root cause lies entirely within the HTML structure of the document you are trying to load.
In your specific scenario, the code attempts to retrieve data from http://myknowledge.org.uk/xml. You are assuming that this URL returns a valid XML document, but the error message suggests otherwise. The parser throws an exception because it encounters malformed markup that violates XML syntax rules.
Let's look closely at the provided "XML Code" snippet:
<?xml version="1.0" encoding="utf-8"?">
<item>
<title>Apple</title>
<!-- ... other elements ... -->
</item>
The most glaring issue is the opening tag itself. The XML declaration <?xml version="1.0" encoding="utf-8"?> is syntactically incorrect for a standard document root, but more importantly, if this snippet represents the actual content returned by the URL, it is missing a root element wrapper or contains unclosed tags. However, the specific error usually points to something simpler: mixed content types.
If file_get_contents($url) returns an HTML page rather than raw XML, SimpleXMLElement will fail immediately. Web servers often serve landing pages (HTML) unless a specific query parameter is passed, or they might return mixed content where parts of the response are HTML and others are XML. If the server returns a standard HTML wrapper around your data, SimpleXML cannot parse it because HTML allows multiple root elements and different attributes that break strict XML parsing logic.
To debug this effectively, you need to inspect the raw output before passing it to the parser. Add a check to see what is actually being returned:
$url = 'http://myknowledge.org.uk/xml';
$response = @file_get_contents($url);
if ($response === false) {
// Handle network errors
} else {
echo "Raw response length: " . strlen($response);
echo "\n\n" . substr($response, 0, 500); // Print first 500 chars for inspection
// Try parsing only if the content looks like XML
try {
$xml = new SimpleXMLElement($response);
foreach ($xml->item as $item) {
echo $item->title . PHP_EOL;
}
} catch (Exception $e) {
echo "Parse error: " . $e->getMessage();
}
}
This approach isolates the failure. If the raw output starts with <!DOCTYPE html> or <html>, you know the server is serving an HTML page, not XML. In that case, you must look for a specific endpoint or parameter that triggers the XML view. For instance, changing the URL to http://myknowledge.org.uk/xml?format=xml might force the server to return the correct data format.
Another potential pitfall involves whitespace and encoding. While SimpleXML is generally robust against BOMs (Byte Order Marks) if handled correctly, if the file returned by file_get_contents contains hidden characters or non-UTF8 bytes that contradict the declared encoding, parsing will fail. You can force UTF-8 decoding to handle potential inconsistencies:
$xmlContent = @file_get_contents($url);
if ($xmlContent) {
// Force re-decode as UTF-8 if mixed with other encodings
$decodedContent = iconv('ISO-8859-1', 'UTF-8//IGNORE', $xmlContent);
// Or simply ensure the server sends Content-Type: application/xml; charset=utf-8
}
Finally, consider the structure of your provided XML example. The root tag appears to be <item>. If the actual response from the URL is a list of items (e.g., <feed><item>...</item><item>...</item></feed>), trying to iterate directly on $xml->item without verifying the root structure first could lead to empty loops or unexpected behavior. Always verify the DOM hierarchy matches your expectations before iterating.
If you are building a larger application, consider using DOMDocument for more flexible error handling and validation before attempting to cast it to SimpleXMLElement. This allows you to check the load() return value and inspect errors via $dom->getLastErrors(), giving you precise feedback on exactly which line caused the parsing failure.