0

I have XML in the following form that I want to parse with PHP (I can't change the format of the XML). Neither SimpleXML nor DOM seem to handle the different namespaces - can anyone give me sample code? The code below gives no results.

    <atom:feed>
        <atom:entry>
            <atom:id />
            <otherns:othervalue />
        </atom:entry>
        <atom:entry>
            <atom:id />
            <otherns:othervalue />
        </atom:entry>
    </atom:feed>



    $doc = new DOMDocument();
    $doc->load($url);
    $entries = $doc->getElementsByTagName("atom:entry");
    foreach($entries as $entry) {
        $id = $entry->getElementsByTagName("atom:id");
        echo $id;
        $othervalue = $entry->getElementsByTagName("otherns:othervalue");
        echo $othervalue;
    }
2
  • 2
    SimpleXMLElement->children, or DOMElement::getElementsByTagNameNS ( string $namespaceURI , string $localName ) (which would be the uri defined by atom, and entry without the atom: prefix), and please, just for the hell of it, find one of the hundreds of similar questions here on SO. This is NOT a new question by a long shot. Commented Jun 14, 2012 at 23:23
  • just $doc->getElementsByTagName("entry"); The keyword in the manual is local name. Commented Jun 14, 2012 at 23:46

2 Answers 2

3

I just want to post with an answer to this awful question. Sorry.

Namespaces are irrelavent with DOM - I just wasn't getting the nodeValue from the Element.

$doc = new DOMDocument();
$doc->load($url);
$feed = $doc->getElementsByTagName("entry");
foreach($feed as $entry) {
    $id = $entry->getElementsByTagName("id")->item(0)->nodeValue;
    echo $id;
    $id = $entry->getElementsByTagName("othervalue")->item(0)->nodeValue;
    echo $othervalue;
}
Sign up to request clarification or add additional context in comments.

Comments

-1

You need to register your name spaces. Otherwise simplexml will ignore them. This bit of code I got from the PHP manual and I used in my own project

$xmlsimple = simplexml_load_string('YOUR XML'); 
$namespaces = $xmlsimple->getNamespaces(true);
$extensions = array_keys($namespaces);

foreach ($extensions as  $extension )
{
    $xmlsimple->registerXPathNamespace($extension,$namespaces[$extension]);
}

After that you use xpath on $xmlsimple

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.