amarelle amarelle - 5 months ago 95
JSON Question

Parse response from XML or JSON API with Httpful PHP

I am using the Httpful PHP library to GET data from an API using either JSON or XML. My code is very simple and returns the response from the url with basic authentication.

$url = "API_URL";
$response = \Httpful\Request::get($url)
->expectsXml() // or ->expectsJson()
->authenticateWith('USERNAME', 'PASSWORD')
->send();
echo "{$response}";


I am successful in displaying the entire response output, but how do I return a single variable?

For example, if I only wanted to receive city from each person, what would this look like? I have tried
echo "{$response->body->city}";
but it does not seem to work.

The XML that is returned by the api is formatted as such:

<ArrayOfPERSON xmlns:i="xxx" xmlns="xxx">
<PERSON>
<CITY></CITY>
<COUNTRY></COUNTRY>
<STATE></STATE>
<STREET1></STREET1>
<STREET2></STREET2>
<WORKPHONE></WORKPHONE>
<ZIP></ZIP>
</PERSON>
</ArrayOfPERSON>


And switching the header to JSON has the data formatted as:

[
{
"STREET1": ""
"STREET2": ""
"CITY": ""
"STATE": ""
"ZIP": ""
"COUNTRY": ""
"WORKPHONE": ""
}
]

Answer

From looking at your JSON structure, it appears the response is nested.

So I believe you'll need to access the body like this:

echo $response->body[0]->STREET1;

Side note: It's always useful to examine your $response by just doing a var_dump($response) when you can't figure out how to navigate it. Just looking at the resulting structure usually makes the answer quite clear!

Comments