vendredi 1 mai 2020

Reading Remote XML Elements with Different Namespaces

So I'm making this webpage that displays dynamic data pulled remotely using XML. But this was no regular XML, this time the elements got namespaces prefixed to the tags. And I can't seem to read the elements without having errors everywhere.

Here is the remote XML when read through my browser:

<search-results
        xmlns="http://www.w3.org/2005/Atom"
        xmlns:dc="http://purl.org/dc/elements/1.1/"
        xmlns:prism="http://prismstandard.org/namespaces/basic/2.0/">
        <opensearch:totalResults>2</opensearch:totalResults>
        <entry>
                <dc:title>Spider-Man</dc:title>
                <dc:creator>Stan Lee</dc:creator>
                <prism:publicationName>Marvel Comics</prism:publicationName>
        </entry>
        <entry>
                <dc:title>Spawn</dc:title>
                <dc:creator>Todd Macfarlane</dc:creator>
                <prism:publicationName>Image Comics</prism:publicationName>
        </entry>
</search-results>

I am trying to print out the opensearch:totalResults, as well as dc:title, dc:creator and prism:publicationName for each entries. What I managed to do without error currently is just read the remote file and display it in the raw XML format to my browser. This is going nowhere, so your kind help is much appreciated! Also, I think I need to learn more about XML namespaces... :(

   <?php
        $options = array('http' => array('method' => "GET",'header' => "Accept: application/xml\r\n"               ));
        $context = stream_context_create($options);
        $url = 'https://api.evian.com/content/search/mambo?query=ID(50409)';
        $searchResult = simplexml_load_string(file_get_contents($url, false, $context)) or die("Error: Cannot create object");

        var_dump($searchResult);
?>



Aucun commentaire:

Enregistrer un commentaire