Yehia Awad
Yehia Awad

Reputation: 2978

PHP XML DOM parsing issue

I am kinda new in xml parsing, I am trying to figure out what is wrong with this piece of code why is it refusing to display any result?

//php code
    $file=file_get_contents("http://".$_SERVER["HTTP_HOST"]."/sitemap.xml");
    $dom = new DOMDocument();
    $dom->loadXML($file);
    $xmlPath = new DOMXPath($dom);
    $arrNodes = $xmlPath->query('//loc');
    foreach($arrNodes as $arrNode){
        echo $arrNode->nodeValue;
    }

//sitemap.xml
    <url>
    <loc>http://calculosophia.com/</loc>
    </url>
    <url>
      <loc>http://calculosophia.com/finance/compound-interest-calculator</loc>
    </url>

I can see that the file is getting retrieved successfully but when var dumping $arrNodes it gives me object(DOMNodeList)[170] I dunno what to do further

Upvotes: 0

Views: 45

Answers (1)

gen_Eric
gen_Eric

Reputation: 227180

$arrNodes = $xmlPath->query('//loc');

This line is returning you a DOMNodeList containing 0 elements. That's because the root element (<urlset>) is declaring a namespace (the xmlns attribute). XPath needs to know about this namespace before you can use it to query the file.

$xmlPath = new DOMXPath($dom);
// The 1st parameter is just name, it can be whatever you want
// The 2nd parameter is the namespace URL (the value of the "xmlns" attribute)
$xmlPath->registerNamespace('sitemap', 'http://www.sitemaps.org/schemas/sitemap/0.9');
$arrNodes = $xmlPath->query('//sitemap:loc');

Upvotes: 2

Related Questions