amarelle amarelle - 1 year ago 165
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')
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">

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

"STREET1": ""
"STREET2": ""
"CITY": ""
"STATE": ""
"ZIP": ""


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!