【问题标题】:Invalid Json response with API CURL PHP [closed]使用 API CURL PHP 的无效 Json 响应 [关闭]
【发布时间】:2021-05-30 23:20:03
【问题描述】:

我正在尝试使用 CURL 调用 API,供应商只允许使用 x-www-form-urlencoded 的内容类型,但它使用其中的 JSON 响应 XML。

然而,在 PHP 的 curl 响应中,它会移除所有的 xml 标签。这是我得到的回应:

{ "描述":"MERCEDES BENZ C 300 AMG LINE MY17 W205 FACELIFT 9 SP AUTOMATIC 9G TRONIC", "注册年份":"2020", “汽车制造商”:{ "CurrentTextValue":"奔驰" }, “汽车模型”:{ “当前文本值”:“C” }, “制作说明”:{ "CurrentTextValue":"奔驰" }, “型号说明”:{ “当前文本值”:“C” }, "座位":"5", “车身”:“轿车”, } 注册的汽车是 MERCEDES BENZ C 300 AMG

问题最后是“句子”,它不是一个有效的 json 字符串,有没有办法删除最后一个 } 之后不需要的“句子”,即“注册的汽车是 MERCEDES BENZ C 300 AMG”

有什么想法???

【问题讨论】:

  • “在 PHP 的 curl 响应中,它将删除所有 xml 标签”...这似乎极不可能。是什么让你相信这一点?如果您只是echo-ing 响应,则应确保您没有将其视为 HTML。在 echo 之前添加 header("Content-type: text/xml"); 任何东西。当然,我只是猜测,但如果您将代码包含在问题中,则不必这样做

标签: php json curl


【解决方案1】:

去掉最后一句相当简单:

<?php
// Assuming we have the response as a string:
$response_string = '{ "Description":"MERCEDES BENZ C 300 AMG LINE MY17 W205 FACELIFT 9 SP AUTOMATIC 9G TRONIC", "RegistrationYear":"2020", "CarMake":{ "CurrentTextValue":"MERCEDES BENZ" }, "CarModel":{ "CurrentTextValue":"C" }, "MakeDescription":{ "CurrentTextValue":"MERCEDES BENZ" }, "ModelDescription":{ "CurrentTextValue":"C" }, "Seats":"5", "Body":"SEDAN", } The registered car is a MERCEDES BENZ C 300 AMG';

// We get the find index of the last closing lambda/parenthesis using strpos
$last_parenthesis = strpos( $response_string, '}', -1 );

// Then use that index to trim the json-string to the correct length using substr
$trimmed_response_string = substr( $response_string, 0, $last_parenthesis );

// Then use json_decode to cast the json-string as a multidimensional variable
$json_data = json_decode( $trimmed_response_string );

var_dump( $json_data );
exit;

希望对你有帮助

【讨论】:

  • 您好,谢谢!经过测试并且思想是正确的,但不确定为什么它返回空白!但是,我设法对您的脚本进行了一些微小的修改,它显示了!
【解决方案2】:

是的,只需找到最后一次出现的 } 并删除它之后的所有内容,如下所示:

$content = "..."; // The content you posted

// Get the json up until and including the last }
$json = substr($content, 0, strrpos($content, '}') + 1);

【讨论】:

  • 您好,谢谢!经过测试并且该方法是正确的,但是它显示了该句子而不是从您的脚本中删除,但是我找到了将其删除的解决方案,即使用您提议的脚本中的相同想法!谢谢!
  • 我的错,我会更新它,已经晚了?
猜你喜欢
  • 1970-01-01
  • 2019-08-15
  • 1970-01-01
  • 2018-02-01
  • 1970-01-01
  • 2019-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多