Parse response from XML or JSON API with Httpful PHP

时间:2016-06-10 16:15:27

标签: php json xml httpful

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": ""
  }
]

1 个答案:

答案 0 :(得分:2)

从查看您的JSON结构看,响应是嵌套的。

所以我相信你需要像这样访问身体:

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

旁注:当您无法弄清楚如何导航时,只需执行$response检查var_dump($response)即可。只看结果结构通常会使答案非常明确!