首页 > 解决方案 > 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);

标签: phpjson

解决方案


此代码有效。原因是接收内容的编码。

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

}

推荐阅读