Search code examples
phpdomdocumentxmldom

Fetching the tags and contents of an xml document with DOM parser in PHP


Consider an XML file like this :

<title>sometitle</title>
<a>
    <abc>content1</abc>
    <xyz>content2</sxyz>
    <metadata>
        <b>
            <c>content3</c>
            <d><attribute></d>
        </b>
    </metadata>
</a>

I use this code to parse my file and i get the output such as :

title : abc

a:content1 content2 content 3

i.e it only parses the first level tags and fails to parse subtags and get the value ,any help is much appreciated since I'am a complete newbie in this.So far this is what I have tried:

$xmlDoc = new DOMDocument();

$xmlDoc->load("somedoc.xml");

$x = $xmlDoc->documentElement;

foreach($x->childNodes AS $item) 
{
    print $item->nodeName . " = " . $item->nodeValue . "<br>";
}

Solution

  • Check the below link for php documentation on haschildnodes() functions.

    You can see samples in the below page for usage.

    http://php.net/manual/en/domnode.haschildnodes.php