simplexml_load_file 无法加载 XML 文件

simplexml_load_file can't load an XML file

我正在尝试对 XML 数据进行一些非常基本的解析,但失败得很惨。

我有一个 metadata.xml 文件:

<?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>

我正在尝试使用以下代码获取特定 XML 条目的结果:

<?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";

?>

这会导致错误:

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

如果我将 XML 文件的内容直接加载到 php 文件中,一切正常。

我在这里阅读了很多相关帖子,但无法弄清楚我哪里出错了。

谢谢!

根据http://php.net/manual/en/simplexmlelement.construct.php我调整了代码:

<?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";

?>