简体   繁体   中英

Parsing XML with multiple namespaces in PHP

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;
    }

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;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM