【问题标题】:How to access XML or transform to JSON in Laravel如何在 Laravel 中访问 XML 或转换为 JSON
【发布时间】:2018-07-20 01:04:43
【问题描述】:

我有这个 XML 响应:

<AuthorisationResult xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://webservice.redletterdays.co.uk/">
<RequestSuccessful>true</RequestSuccessful>
<ErrorMessage/>
<Token>3d3d4a94-87fe-414c-ae0a-fd0e0c4c0060</Token>
</AuthorisationResult>

这就是我写的时候得到的:

return $res;

我如何访问令牌?

我试试:

return $res->Token; 

还有

return $res->children();

但此代码返回错误...

SO,我如何访问 XML 中的 Token 或如何转换为 JSON 并轻松访问 $res->Token 等 Token ...

【问题讨论】:

  • 把你的xml作为文本而不是图片
  • 我把它写成文本
  • $xml = simplexml_load_string($res); echo $xml-&gt;Token;
  • 我像这样解决: res = json_encode(simplexml_load_string($res->getBody())); $res = json_decode($res); $token = $res->令牌;

标签: php json xml laravel object


【解决方案1】:

我解决了我的问题:

$res = json_encode(simplexml_load_string($res->getBody()));
$res = json_decode($res);
$token = $res->Token;

【讨论】:

    【解决方案2】:

    试试这个:

    $json = $res->getBody();
    $array = json_decode($json);
    
    dump($array);
    

    【讨论】:

    • 我已经尝试过了,但我得到了:simplexml_load_string() 期望参数 1 是字符串,给定对象
    • @AleksPer 在这种情况下您已经有一个 XML 对象,请查看我的更新答案
    • 是的,但是我得到了空数组,比如 '[ ]'
    • @AleksPer 你是如何获得$res 对象的?
    • 我从 API 获取 $res 对象作为响应
    猜你喜欢
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-03
    • 1970-01-01
    相关资源
    最近更新 更多