simplexml\u加载\u文件无法加载XML文件

simplexml\u加载\u文件无法加载XML文件,simplexml,php-7,Simplexml,Php 7,我试图对XML数据进行一些非常基本的解析,但失败得很惨 我有一个metadata.xml文件: <?xml version="1.0" encoding="UTF-8" ?> <metadata> <page> <filename>products.php</filename> <title>Best selection of products

我试图对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";

?>
这将导致一个错误:

警告:SimpleXMLElement::_构造:实体:第4行:解析器错误:应为开始标记,“根据我调整代码如下:

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

?>

在xml中添加xml doctypefile@EvgenyKolyakov非常感谢。我像这样添加了doctype,但仍然得到相同的结果:]>products.php美国Anytown的最佳产品选择我们销售高质量的产品,不幸的是,您应该添加它,直到产生相同的结果,如果您尝试将其加载为包含文件内容和simplexml加载字符串的字符串,会发生什么?