guzzle 从响应中读取值

guzzle read value from response

我将 Guzzle 与 Laravel 结合使用,通过 HTTP 从外部 API 获取对象。 API return XML 类似这样的对象 (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 但它不起作用或不再受支持。

有什么想法吗? 谢谢

您从响应中得到的是 xml 内容。由于浏览器与 XML 的兼容性,您只能看到文本。您只需要 SimpleXML class of php 即可根据 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;

希望对您有所帮助。