我正在使用XMLReader和SimpleXML的组合,而且,由于我在阅读XML时使用PHP非常新,我想知道为什么第一行(注释掉的)2行代码没有返回任何内容?第二个版本(在注释中注明)确实返回结果。
返回的错误是:
XPath query failed for bio
所以,我不确定失败是在xmlreader代码还是xpath变量中。
感谢任何线索。
PHP:
<?php
$secondary_user_id = "jsmith";
$url_bio = "bio_short.xml";
$reader = new XMLReader();
//load the selected XML file to the DOM
$reader->open($url_bio);
while ($reader->read())
{
// 'property' in the line below is the name of our main XML node
if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == 'Users')
{
//begin - 1st version with DOMDocument
//$doc = new DOMDocument('1.0','UTF-8');//
//$xml_bio_report = simplexml_import_dom($doc->importNode($reader->expand(),true));//
//end - 1st version
//begin - 2nd version with SimpleXMLElement
$xml_bio_report = new SimpleXMLElement($reader->readOuterXML());
//end - 2nd version
$xml_bio_report->registerXPathNamespace('xlink','http://www.w3.org/1999/xlink');
$xml_bio_report->registerXPathNamespace('dmu','http://www.digitalmeasures.com/schema/user-metadata');
//echo $xml_bio_report->Users->User;
$xml_bio_report_abbrev = $xml_bio_report->xpath('//User[@SecondaryID="'.$secondary_user_id.'"]');
if ($xml_bio_report_abbrev){
echo '<h1>'.$xml_bio_report_abbrev[0]['username'].'</h1>';
echo '<h1>'.$xml_bio_report_abbrev[0]['SecondaryID'].'</h1>';
$user_name = $xml_bio_report_abbrev[0]['username'];
$secondary_id = $xml_bio_report_abbrev[0]['SecondaryID'];
//var_dump($xml_bio_report_abbrev);
} else {
echo 'XPath query failed for bio';
}
$user_name=trim($user_name);
echo "user_name is...".$user_name."<br>";
echo "secondary_id is...".$secondary_id."<br>";
}
}
?>
XML(&#39; bio_short.xml&#39;):
<?xml version="1.0" encoding="UTF-8"?>
<Users xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:dmu="http://www.digitalmeasures.com/schema/user-metadata">
<User username="john-smith" dmu:userId="14" SecondaryID="jsmith" enabled="false">
<FirstName>John</FirstName>
<MiddleName>L</MiddleName>
<LastName>Smith</LastName>
<Email>john-smith@email.com</Email>
<LocalAuthentication/>
<Item xlink:type="simple" xlink:href="/login/service/v4/User/USERNAME:john-smith"/>
</User>
<User username="mary-smith" dmu:userId="19" SecondaryID="msmith">
<FirstName>Mary</FirstName>
<LastName>Smith</LastName>
<Email>mary-smith@email.com</Email>
<LocalAuthentication/>
<Item xlink:type="simple" xlink:href="/login/service/v4/User/USERNAME:mary-smith"/>
</User>
</Users>
更新: 当我重新编写如下代码时,它使用此page作为参考返回结果 与复合语句(注释掉)相反,差异是否会从构造变量的顺序产生?
if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == 'Users')
{
$node = $reader->expand();
$doc = new DOMDocument('1.0','UTF-8');
$n = $doc->importNode($node,true);
$doc->appendChild($n);
$xml_bio_report = simplexml_import_dom($n);
//$xml_bio_report = simplexml_import_dom($doc->importNode($reader->expand(),true));