使用此代码时,我收到了此类错误消息。
无法显示XML页面 无法使用样式表查看XML输入。请更正错误,然后点击>刷新按钮,或稍后重试。 XML文档中只允许一个顶级元素。处理资源
时出错<c>text</c><c>stuff</c>
<?php
$string = <<<XML
<a>
<b>
<c>text</c>
<c>stuff</c>
</b>
<d>
<c>code</c>
</d>
</a>
XML;
$xml = new SimpleXMLElement($string);
echo $xml->asXML();
$result = $xml->xpath('/a/b/c');
foreach ($result as $id => $child) {
echo "<c>".(string)$child."</c>";
}
答案 0 :(得分:1)
检查您输出的XML源,您的XML缺少文档元素并转义。
更好的方法是使用DOM复制节点:
<?php
$string = <<<XML
<a><b><c>text</c><c>stuff</c></b><d><c>code</c></d></a>
XML;
// load source XML and create Xpath instance
$source = new DOMDocument();
$source->loadxml($string);
$xpath = new DOMXpath($source);
// create target document with document element
$target = new DOMDocument();
$root = $target->appendChild($target->createElement('e'));
// copy nodes from source to target
foreach ($xpath->evaluate('/a/b/c') as $child) {
$root->appendChild($target->importNode($child));
}
// output target
echo $target->saveXml();
答案 1 :(得分:0)
在此代码下面..我需要检索特定节点,即代码意味着我想要做的事情。
<?php
$string = <<<XML
<a>
<b>
<c>text</c>
<c>stuff</c>
</b>
<b>
<c>code</c>
</b>
<d>
<c>item</c>
</d>
</a>
XML;
$xml = new SimpleXMLElement($string);
$xml->asXML()."<br>";
// echo "<c>".(string)$child."</c>";
foreach( $xml->children() AS $child )
{
//run any query you want on the children.. they are also nodes.
$name1 = $child;
//echo "<pre><c></pre>".$name1."<pre><c></pre><br>";
foreach( $name1->children() AS $child1 )
{
$name2 = $child1->getName();
$child2=$child1;
// echo $name2."--".$child2;
echo "<".$name2.">".$child2."<⁄".$name2.">"."<br>";
}
}
?>