![](/img/trans.png)
[英]php SimpleXMLElement get children with another xml namespace
[英]PHP SimpleXMLElement, get element and its children as XML
假设我有以下XML:
<Book>
<bookname>thename</bookname>
<chapters>
<chapter>
<name>chapter1</name>
</chapter>
<chapter>
<name>chapter2</name>
</chapter>
</chapters>
</Book>
如何获得XML,如下所示:
<chapters>
<chapter>
<name>chapter1</name>
</chapter>
<chapter>
<name>chapter2</name>
</chapter>
</chapters>
一种方法是手动删除不需要的元素,例如
$resultXML = new SimpleXMLElement($inputXML);
unset($resultXML->bookname);
$resultXML = $resultXML->asXml();
echo format_result($resultXML,$format);
但是,如果我有一个带有许多不需要的注释的大型XML,这将很乏味。 知道谁使用其名称提取所需元素吗?
开始了:
<?php
$inputXML ="
<Book>
<bookname>thename</bookname>
<chapters>
<chapter>
<name>chapter1</name>
</chapter>
<chapter>
<name>chapter2</name>
</chapter>
</chapters>
</Book>
";
/* Load from file:
$parseXML = simplexml_load_file( $fileURL );
*/
$parseXML = simplexml_load_string( $inputXML );
$chapters = $parseXML->chapters->asXML();
echo $chapters;
?>
注意:您的xml必须格式正确,当前<Book>
没有结束标记。
XML的子节点本身就是SimpleXMLElements,因此您也可以在它们上调用axXml方法。
由于您的XML中只有一个chapters
节点,因此
$resultXML->chapters->asXml()
会做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.