Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using wp_remote_get to work with XML in WordPress

Tags:

php

xml

wordpress

I suspect I'm missing something really basic and obvious, so apologies in advance!

I had been using simple_xml_load to work with an XML file, but my client's hosting provider blocks the loading of external files through this method. I'm now trying to rebuild my work using the wp_remote_get function built into WordPress.

Here's my code (note: the key and shelter ID are generic in this example):

$url = "http://api.petfinder.com/shelter.getPets?key=1234&count=20&id=abcd&status=A&output=full";
$pf_xml = wp_remote_get( $url );
$xml = wp_remote_retrieve_body($pf_xml);

Using this, I can retrieve an array of all the data I need, but I cannot figure out how to target specific data. Here is what's output from print_r($xml):

<petfinder xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://api.petfinder.com/schemas/0.9/petfinder.xsd">
    <header>
        <version>0.1</version>
        <timestamp>2013-03-09T15:03:46Z</timestamp>
        <status>
        <code>100</code>
        <message/>
        </status>
    </header>
    <lastOffset>5</lastOffset>
    <pets>
        <pet>
            <id>13019537</id>
            <name>Jordy</name>
            <animal>Dog</animal>
        </pet>
        <pet>
            <id>13019888</id>
            <name>Tom</name>
            <animal>Dog</animal>
        </pet>
    </pets>
</petfinder>

If I wanted to echo the status code, for example, how would I do that? Using simplexml, I would write $xml->header->status->code. I can't seem to figure out what the code structure is to do something similar with arrays using wp_remote_get.

Thanks in advance!

like image 879
Chris Ferdinandi Avatar asked Mar 09 '13 15:03

Chris Ferdinandi


1 Answers

Your code so far does retrieve the XML as string:

$url      = "http://api.petfinder.com/shelter.getPets?key=1234&count=20&id=abcd&status=A&output=full";
$response = wp_remote_get($url);
$body     = wp_remote_retrieve_body($response);

To load a string (instead of a URL) into a SimpleXMLElement as you did before with simplexml_load_file (you didn't show the concrete code so I assume you did it this way based on your description) you now need to load the string with simplexml_load_string instead:

$xml  = simplexml_load_string($body);
$code = $xml->header->status->code;

I slightly changed your variable names (especially with the wp_remote_* functions) to make it more clear for what those variables carry.

like image 181
hakre Avatar answered Oct 06 '22 16:10

hakre