【问题标题】:guzzle read value from responseguzzle 从响应中读取值
【发布时间】:2018-12-19 11:49:22
【问题描述】:

我将 Guzzle 与 Laravel 一起使用,通过 HTTP 从外部 API 获取对象。 API 返回类似这样的 XML Object (https://www.w3schools.com/php/note.xml)

我需要检查响应正文的一个值。这是我的代码:

$client = new \GuzzleHttp\Client();    
$res = $client->request('GET', 'https://www.w3schools.com/php/note.xml');    
$stringBody = (string) $res->getBody()->getContents();
echo $stringBody;

这工作正常,我的意思是它显示身体如下图

但我无法获得一个值? 我尝试了不同的方法,但没有一个有效! 例如,这样:

$result = starts_with($stringBody, 'Tove');

splitName = explode(' ', $res->getBody()); 
$first_name = $splitName[0];
echo $first_name;

非工作?我认为它认为正文是空的?

我尝试使用 json_decode,但它不起作用或不再受支持。

有什么想法吗? 谢谢

【问题讨论】:

  • 尝试使用dd($stringBody) 输出$stringBody。这样你就可以看到变量的确切值了。

标签: php laravel guzzle


【解决方案1】:

您从响应中得到的是 xml 内容。由于浏览器与 XML 的兼容性,您只能看到文本。您只需要 PHP 的 SimpleXML 类即可根据 XML 节点获取内容。这是示例代码

    $client = new \GuzzleHttp\Client();
    $res = $client->request('GET', 'https://www.w3schools.com/php/note.xml');
    $stringBody = (string) $res->getBody()->getContents();
    $xml =  simplexml_load_string($stringBody);
    echo $xml->to;

希望对您有所帮助。

【讨论】:

  • 谢谢。这就是我要找的:)
猜你喜欢
  • 1970-01-01
  • 2015-08-21
  • 1970-01-01
  • 1970-01-01
  • 2020-05-09
  • 2014-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多