首页 > 解决方案 > 使用 API CURL PHP 的无效 Json 响应

问题描述

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

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

{ "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", } 注册车辆为 MERCEDES BENZ C 300 AMG

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

任何的想法???

标签: phpjsoncurl

解决方案


删除最后一句相当简单:

<?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;

希望这会有所帮助


推荐阅读