0

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

12
  • can you please explain why -1 ? Commented Dec 29, 2014 at 21:11
  • Change $arrNode->item(0)->nodeValue to $arrNode->nodeValue Commented Dec 29, 2014 at 21:13
  • @RocketHazmat still nothing Commented Dec 29, 2014 at 21:14
  • What do you see if you do var_dump($arrNode) inside the loop? Commented Dec 29, 2014 at 21:15
  • 1
    I see your issue. Your XML file is invalid. There's no root node. Is what you've posted here the entirety of your XML file? Commented Dec 29, 2014 at 21:18

1 Answer 1

2
$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');
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks it works! I am old in PHP and this thing would never come to my mind though I don't know why they -1 me ? is it kinda of stupid ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.