Reputation: 14250
I am having an issue getting xml data in php
My xml is fairly complicated and there are several nested children in the tag.
xml
?xml version="1.0" encoding="UTF-8"?>
<book id="5">
<title id="76">test title</title>
<figure id="77"></figure>
<ch id="id78">
<aa id="80"><emph>content1</emph></aa>
<ob id="id_84" page-num="697" extra-info="4"><emph type="bold">opportunity.</emph></ob>
<ob id="id_85" page-num="697" extra-info="5"><emph type="bold">test data.</emph></ob>
<para id="id_86" page-num="697">2008.</para>
<body>
..more elements
<content>more contents..
</content>
</body>
</ch>
MY codes
//I need to load many different xml files.
$xml_file = simplexml_load_file($filename);
foreach ($xml_file->children() as $child){
echo $child->getName().':'. $child."<br>";
}
The codes above would only display
book, title, figure, ch
but not the elements inside the ch
tag. How do I display all the element inside each tag? Any tips? Thanks a lot!
Upvotes: 0
Views: 146
Reputation: 3996
Two things:
You need to match your <ob>
</objective>
tags.
Your foreach needs to be recursive. You should check if each item in your foreach has a child, then recursively foreach over that elements. I'd recommend using a separate function for this that you recursively call.
Example:
$xml_file = simplexml_load_file($filename);
parseXML($xml_file->children());
function parseXML($xml_children)
{
foreach ($xml_children as $child){
echo $child->getName().':'. $child."<br>";
if ($child->count() > 0)
{
parseXML($child->children());
}
}
}
Upvotes: 2
Reputation: 6950
You need to do resursive call
parseAllXml($xml_file);
function parseAllXml($xmlcontent)
{
foreach($xmlcontent->children() as $child)
{
echo $child->getName().':'. $child."<br>";
$is_further_child = ( count($child->children()) >0 )?true:false;
if( $is_further_child )
{
parseAllXml($child);
}
}
}
Upvotes: 1