Search code examples
phpsimplexml

simplexml_load_file can't load an XML file


I'm trying to do some very basic parsing of XML data but am failing miserably.

I have a metadata.xml file as such:

<?xml version="1.0" encoding="UTF-8" ?>
<metadata>
    <page>
        <filename>products.php</filename>
        <title>Best selection of products in Anytown, USA</title>
        <description>We sell quality products</description>
    </page>
    <page>
        <filename>services.com</filename>
        <title>Great services anywhere within Anytown</title>
        <description>Our services are pretty good</description>
    </page>
</metadata>

I'm attempting to get a result for a specific XML entry using the code below:

<?php
    
$str = simplexml_load_file("metadata.xml") or die("Couldn't load file");

$data = new SimpleXMLElement($str);
// Find the element with specific filename
$nodes = $data->xpath('//metadata/page/filename[.="products.php"]/parent::*');
$result = $nodes[0];
echo "Title: " . $result->title . "\n";
echo "Description: " . $result->description . "\n";

?>

This results in an error:

Warning: SimpleXMLElement::__construct(): Entity: line 4: parser error : Start tag expected, '<' not found in /var/www/html/php_xml_test.php on line 10

Fatal error: Uncaught Exception: String could not be parsed as XML in /var/www/html/php_xml_test.php:10 Stack trace: #0 /var/www/html/php_xml_test.php(10): SimpleXMLElement->__construct('\n\t\n\t\n') #1 {main} thrown in /var/www/html/php_xml_test.php on line 10

If I load the content of the XML file right into the php file everything works fine.

I've read through a bunch of related posts here but can't figure out where I'm going wrong.

Thanks!


Solution

  • As per http://php.net/manual/en/simplexmlelement.construct.php I adjusted the code like that:

    <?php
    
    $data = new SimpleXMLElement('metadata.xml', 0, TRUE);
    // Find the element with specific filename
    $nodes = $data->xpath('//metadata/page/filename[.="services.php"]/parent::*');
    $result = $nodes[0];
    echo "Title: " . $result->title . "\n";
    echo "Description: " . $result->description . "\n";
    
    ?>