如何解码JSON以获取变量

时间:2017-04-05 08:03:15

标签: php json

JSON网址:https://www.mylivepolls.com/api.php
我试图解码这个json,但得到错误。我在这做错了什么?
任何帮助将不胜感激。

$json = file_get_contents("https://www.mylivepolls.com/api.php");
$data = json_decode($json);
$var = $data->mchdata->match[0]->id;
echo $var;

1 个答案:

答案 0 :(得分:0)

尝试此操作,或者您可以使用{jar}来使用curl代替file_get_contents

$json = file_get_contents("https://www.mylivepolls.com/api.php");
$data = json_decode($json, true);

if(is_array($data) && isset($data['mchdata']) && isset($data['mchdata']['match'])) {
    $matches = $data['mchdata']['match'];

    if(is_array($matches)) {
        foreach($matches as $match) {
            $id = $match['id'];
        }
    }
    $current_match = current($matches);
    echo $var = $current_match['id'];
}

使用卷曲:

$ckfile = tempnam (sys_get_temp_dir(), 'apicookiename');

$handle = curl_init("https://www.mylivepolls.com/api.php");

curl_setopt ($handle, CURLOPT_COOKIEJAR, $ckfile);
curl_setopt ($handle, CURLOPT_COOKIEFILE, $ckfile);

curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($handle, CURLOPT_FOLLOWLOCATION, TRUE);

$json = curl_exec($handle); 
$data = json_decode($json, true);

if(is_array($data) && isset($data['mchdata']) && isset($data['mchdata']['match'])) {
    $matches = $data['mchdata']['match'];

    if(is_array($matches)) {
        foreach($matches as $match) {
            $id = $match['id'];
        }
    }
    $current_match = current($matches);
    echo $var = $current_match['id'];
}

由于