JSON错误“试图获取非对象的属性”

时间:2018-12-21 15:27:19

标签: php json

我的代码有问题:

看我的JSON:

{ "informations": { "version": "1_0_1_ALPHA", "terms": "https://dev-time.eu/fr/", "update": "20/12/2018", "game": "bo4", "reponse": "success"	} , "multiplayer": { "map_code": "mp_urban", "map": "Arcenal", "dlc": "0", "date": "Sortie du jeu"	} }

我的代码(PHP):

<?php $maps_name = file_get_contents("https://dev-time.eu/api/api__callofduty?game=bo4&map=mp_urban&type=mp"); ?>
        <?php $parsed_map = json_decode($maps_name); ?>
        <?= var_dump($maps_name); ?>
        "<?= $parsed_map->{'informations'}->{'version'}; ?>"

我的var_dump返回:

string(354) "{ "informations": { "version": "1_0_1_ALPHA", "terms": "https://dev-time.eu/fr/", "update": "20/12/2018", "game": "bo4", "reponse": "success"	} , "multiplayer": { "map_code": "mp_jungle2", "map": "Jungle", "dlc": "0", "date": "Sortie du jeu"	} }" "

enter image description here

1 个答案:

答案 0 :(得分:2)

这是您的生命救星:)

 function remove_utf8_bom($str)
 {
    $bom_char = pack('H*','EFBBBF');
    return preg_replace("/^$bom_char/", '', $str);
  }
带有CURLfile_get_contents()

完整工作代码

<?php
function remove_utf8_bom($text)
{
    $bom = pack('H*','EFBBBF');
    $text = preg_replace("/^$bom/", '', $text);
    return $text;
}

$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => "https://dev-time.eu/api/api__callofduty?game=bo4&map=mp_urban&type=mp",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_HTTPHEADER => array(
        "Content-Type: application/json",
    ),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
    echo "cURL Error #:" . $err;
} else {
    $response = remove_utf8_bom($response);   
}
$d = json_decode($response);
echo $d->informations->version;
?>