Suppose I have the following XML:
<Book>
<bookname>thename</bookname>
<chapters>
<chapter>
<name>chapter1</name>
</chapter>
<chapter>
<name>chapter2</name>
</chapter>
</chapters>
</Book>
How can I get an XML as follows:
<chapters>
<chapter>
<name>chapter1</name>
</chapter>
<chapter>
<name>chapter2</name>
</chapter>
</chapters>
One way is to manually remove unwanted elements eg
$resultXML = new SimpleXMLElement($inputXML);
unset($resultXML->bookname);
$resultXML = $resultXML->asXml();
echo format_result($resultXML,$format);
But if I have a large XML with many unwanted notes, this is tedious. Any idea who to extract the required element using its name?
Here we go:
<?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;
?>
Note: Your xml must be well-formated, currently your <Book>
has no closing tag.
The sub-nodes of your XML are themselves SimpleXMLElements – so you can just call the axXml method on them as well.
Since you only have one chapters
node in your XML, simply
$resultXML->chapters->asXml()
will do.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.