简体   繁体   English

使用Httpful PHP解析XML或JSON API的响应

[英]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. 我正在使用Httpful PHP库从使用JSON或XML的API获取数据。 My code is very simple and returns the response from the url with basic authentication. 我的代码非常简单,并使用基本身份验证从url返回响应。

$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}"; 我已经试过echo "{$response->body->city}"; but it does not seem to work. 但它似乎不起作用。

The XML that is returned by the api is formatted as such: api返回的XML格式如下:

<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: 并将标头切换为JSON时,数据格式为:

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

From looking at your JSON structure, it appears the response is nested. 通过查看您的JSON结构,看起来响应是嵌套的。

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. 旁注:当您不知道如何导航时,仅通过执行var_dump($response)来检查$response总是有用的。 Just looking at the resulting structure usually makes the answer quite clear! 只看结果结构通常会使答案很清楚!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM