Why is json_decode failing?

时间:2013-07-16 作者:yoyodyne

我试图确定这是否与我在使用最新版本的Wordpress时在服务器上安装最新版本的PHP有关。或者如果我只是做错了:

以下是正确返回值的函数(我在执行echo或var转储时可以看到它们):

    function my_Get_CURL (){
    $url        = \'http://someotherserver/event/94303?radius=30\';
    //  Initiate curl
        $ch = curl_init();
    // Disable SSL verification
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    // Will return the response, if false it print the response
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    //header
    $headers = array(
        \'Content-type: application/json\'
    );
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    // Set the url
        curl_setopt($ch, CURLOPT_URL,$url);
    // Execute
        $json_content=curl_exec($ch);

    $json = json_decode($json_content, true);
   // echo $json_content;
        return array(
             \'distance\' => $json->distance,
            \'data\' => $json->data
        );
    }

    add_filter(\'the_content\', \'my_Get_CURL\', 1,3);
下面是var\\u dump或echo产生的结果:

[{"distance": 0.0, "data": {"event_id": "1179", "post_id": "1564", "location_id": "19", "location_postcode": "94301"}}, {"distance": 2.162680661505968, "data": {"event_id": "1193", "post_id": "1578", "location_id": "19", "location_postcode": "94301"}}
是我吗?或者,正如我在Wordpress中读到一些关于json\\U解码的散漫报道一样,是因为我使用的是php v5。3.2?

我应该使用wp\\u remote\\u retrieve\\u body吗?这与我使用的卷曲选项有什么区别?

此外,我也尝试过这种方法。。这是教科书。仍然没有返回任何内容:

function my_wpRemote() {

    // Send GET request to remote API
    $api_url = \'http://remoteserver/event/94303?radius=30\';
    $api_response = wp_remote_get( $api_url );

    // Get the JSON object
    $json = wp_remote_retrieve_body( $api_response );

    // Make sure the request was succesful or return false
    if( empty( $json ) )
        return false;

    // Decode the JSON object
    // Return an array
    $json = json_decode( $json );

    return array(
        \'distance\'  => $json->distance,
        \'data\' => $json->data
    );
}
add_filter(\'the_content\', \'my_wpRemote\', 1,3);

1 个回复
SO网友:Kaushik Dey

使用print_r(); 并转化为一个变量以进一步工作。示例:

$convertObj = json_decode($fetchJobs);
$jobArray = print_r($convertObj->data, true);

结束