1

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": ""
  }
]
2
  • @jszobody Yes, this worked! It also appears to be case sensitive. $response->body[0]->CITY is the correct output. Commented Jun 10, 2016 at 16:36
  • awesome, glad to help! I just posted it as an answer below, can you accept it? Commented Jun 10, 2016 at 16:38

1 Answer 1

2

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.