我试图对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 :: __ construct():实体:第4行:解析器错误:期望开始标记,&#39;&lt;&#39;在第10行的/var/www/html/php_xml_test.php中找不到
致命错误:未捕获异常:无法在/var/www/html/php_xml_test.php:10中将字符串解析为XML堆栈跟踪:#0 /var/www/html/php_xml_test.php(10):SimpleXMLElement- &gt; __构造(&#39; \ n \ t \ n \ t \ n&#39;)第10行/var/www/html/php_xml_test.php中抛出的#1 {main}
如果我将XML文件的内容直接加载到php文件中,一切正常。
我在这里阅读了一些相关的帖子,但无法弄清楚我哪里出错了。
谢谢!
答案 0 :(得分:1)
根据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";
?>