简体   繁体   中英

How do extract child element in XML using DOM in PHP 5.0?

I am having the XML like this

  <?xml version="1.0" encoding="utf-8"?>
  <root>
      <mynode catid="10" catname="Animals" label="Animals" catdesc="" parent_id="2">
         <mynode catid="11" catname="Lions" label="Lions" catdesc="" parent_id="10">
           <mynode catid="12" catname="lion" label="lion" catdesc="" parent_id="11"/>
         <mynode catid="13" catname="lioness" label="lioness" catdesc="" parent_id="11"/>
        </mynode>
       </mynode>
    </root>

From this I want to remove

<?xml version="1.0" encoding="utf-8"?>
<root>

and

</root>

So expected result is

        <mynode catid="10" catname="Animals" label="Animals" catdesc="" parent_id="2">
         <mynode catid="11" catname="Lions" label="Lions" catdesc="" parent_id="10">
           <mynode catid="12" catname="lion" label="lion" catdesc="" parent_id="11"/>
         <mynode catid="13" catname="lioness" label="lioness" catdesc="" parent_id="11"/>
        </mynode>
       </mynode>

How can I do this?

Edit 1:TO Phil

        $dom = new DomDocument();
       //$dom->preserveWhitespace = false;
     $dom->load('treewithchild.xml'); 

function DOMinnerHTML($element) 
{ 
$innerHTML = ""; 
$children = $element->childNodes; 

foreach ($children as $child) 
{ 

    $tmp_dom = new DOMDocument(); 
    $tmp_dom->appendChild($tmp_dom->importNode($child, true)); 
    $innerHTML.=trim($tmp_dom->saveXML()); 
    echo $tmp_dom->saveXML();
} 
return $innerHTML; 
 } 
  $dom->preserveWhiteSpace = false; 

  $domTable = $dom->getElementsByTagName("mynode"); 

    foreach ($domTable as $tables) 
   { 
//echo $tables;
       DOMinnerHTML($tables); 
  } 

As you want the inner markup of the <root> node, that is the element who's child nodes you'll want to iterate. You can access this element using the DOMDocument::documentElement property.

Try this (tested and working)

$doc = new DOMDocument;
$doc->load('treewithchild.xml');
$inner = '';
foreach ($doc->documentElement->childNodes as $child) {
    $inner .= $doc->saveXML($child);
}
echo $inner;

I expect that the root element is returned also, you have to know that for each xml file an is added impliicitly, even if it exists in your file. so try to do this
$children = $element->childNodes->childNodes;
i think that would help you.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM