php - 使用 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”
任何的想法???
解决方案
删除最后一句相当简单:
<?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;
希望这会有所帮助
推荐阅读
- maven - IntelliJ 无法从 org.springframework.security.oauth2.core.ClientAuthenticationMethod 解析符号核心
- ruby - 创建一个将文本放入 .txt 文件的插件
- javascript - TinyMCE:如何永久激活拼写检查器
- react-native - 将 zIndex 设置为组件后视图消失
- c# - 从另一个帖子返回视图
- mysql - 无法通过主机名从同一网络中的 Spring Boot 容器访问 mysql 容器
- macos - AirDrop 在 macOS 中禁用检测和设置
- php - PHP 回调 URL 不包括 ?a=complete
- hive - 当我创建一个新提要时,我遇到了这样的问题 保存提要重复键 ProcessGroupDTO:b20b995a-0165-1000-0479-b059731bba5b 时出错
- java - Spring Boot 手动内容协商