php - PHP print_r 不返回 json 请求
问题描述
以下代码运行没有任何错误,但它不返回任何内容。
如果我将它粘贴到我的浏览器中,它会返回我正在寻找的信息,我也可以用另一个 URL 替换它,它工作得很好。
$ch = curl_init();
$url = 'https://api.coronavirus.data.gov.uk/v1/data?filters=areaName=Somerset&structure={"date":"date","areaName":"areaName","areaCode":"areaCode","newCasesByPublishDate":"newCasesByPublishDate","cumCasesByPublishDate":"cumCasesByPublishDate","newDeathsByDeathDate":"newDeathsByDeathDate","cumDeathsByDeathDate":"cumDeathsByDeathDate"}';
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$resp = curl_exec($ch);
$decode =json_decode($resp);
print_r($decode);
curl_close($ch);
解决方案
此代码有效。原因是接收内容的编码。
try {
$ch = curl_init();
// Check if initialization had gone wrong*
if ( $ch === false ) {
throw new RuntimeException( 'failed to initialize' );
}
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL,
'https://api.coronavirus.data.gov.uk/v1/data?filters=areaName=Somerset&structure={"date":"date","areaName":"areaName","areaCode":"areaCode","newCasesByPublishDate":"newCasesByPublishDate","cumCasesByPublishDate":"cumCasesByPublishDate","newDeathsByDeathDate":"newDeathsByDeathDate","cumDeathsByDeathDate":"cumDeathsByDeathDate"}' );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Solution is here. Response is the compressed content which your curl failed to detect. Empty encoding means to handle any type of encoding. It should solve your issue.
curl_setopt($ch, CURLOPT_ENCODING, '');
$content = curl_exec( $ch );
curl_close( $ch );
if ( $content === false ) {
throw new RuntimeException( curl_error( $ch ), curl_errno( $ch ) );
}
/* Process $content here */
$decode = json_decode( $content );
var_dump( $decode );
// Close curl handle
curl_close( $ch );
} catch ( RuntimeException $e ) {
trigger_error(
sprintf(
'Curl failed with error #%d: %s',
$e->getCode(),
$e->getMessage()
),
E_USER_ERROR
);
}
推荐阅读
- python - Dask Dataframe 中的 Groupby、Unstack 和 Plot
- javascript - 无法重现错误:没有“新”就无法调用类构造函数 DateTimeFormat
- python - 模型要么未安装,要么是抽象的 - Django、Python
- android - 如何使用okhttp创建数据流并写入android中的设备
- javascript - babel-jest : this.setDynamic 不是一个函数(迁移到 Jest 25)
- javascript - javascript中奇怪的字符串值
- django - 登录时 Django 用户丢失组(但不是权限)
- rust - 在 Rust 的 match arm 中调用多个函数
- c# - 主顶部菜单和右键单击上下文菜单之间的 WPF 共享菜单
- python - pandas : groupby + 条件 + 遍历一列