Aller au contenu

Fixing the 'String could not be parsed as XML' PHP error message

Ce contenu n’est pas encore disponible dans votre langue.

When working with XML data in PHP, you may encounter the error:

Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML'

This error occurs when PHP attempts to parse invalid or improperly formatted XML.

  • The XML data is not valid (missing tags, mismatched elements, or incorrect nesting).
  • The XML contains non‑standard characters or uses an unsupported character set.
  • The XML is incomplete or corrupted.
  • The script is trying to load a string that is not XML at all.
  • Use an online validator such as xmlvalidation.com to check syntax.
  • Ensure all tags are properly opened and closed.
  • Confirm encoding matches the XML declaration (e.g., <?xml version="1.0" encoding="UTF-8"?>).
  • Make sure the XML string uses UTF‑8 or another supported encoding.
  • Remove or replace invalid characters.
  • Example with simplexml_load_string():

    <?php
    $xmlString = '<?xml version="1.0"?><root><item>Test</item></root>';
    $xml = simplexml_load_string($xmlString);
    if ($xml === false) {
    echo "Failed to parse XML";
    foreach(libxml_get_errors() as $error) {
    echo $error->message;
    }
    } else {
    echo "XML parsed successfully";
    }
    ?>
  • This approach provides detailed error messages using libxml_get_errors().

  • If XML is coming from an external API or file, check the source for corruption.
  • Log the raw XML string before parsing to identify issues.

Cette page vous a-t-elle aidé ?