Search code examples
phpxmldom

how to parse xml through DOM in php


<?xml version="1.0" encoding="utf-8"?>
<info>
   <report id="1">
      <book>
          <title>A</title>
      </book>
      <author>
          <name>xyz</name>
      </author>
   </report>
   <report id="2">
       <book>
           <title>B</title>
       </book>
       <author>
           <name>xyz</name>
       </author>
   </report>
   <report id="3">
       <book>
           <title>C</title>
       </book>
       <author>
           <name>xyz</name>
       </author>
  </report>
</info>

this is my xml and i want to retrieve each report and save it to database
I have load the xml file to dom and can retrive value by using nodeValue.By using nodeValue i am getting values like A and XYZ but I want the value is in xml formatted
<book> <title>A</title> </book> <author> <name>xyz</name> </author>


Solution

  • I guess that you are trying to get each report node as well as its contents. You may do the following:

    <?php
        $doc = DOMDocument::loadXML(' x m l  s t r i n g ');
    
        $reportNodeList = $doc->getElementsByTagName('report');
        foreach($reportNodeList as $reportNode) {
            echo htmlspecialchars($doc->saveXML($reportNode));
        }
    ?>