JSON跳过第一行和最后一行文件

时间:2015-05-12 17:28:22

标签: php json

如何让json_decode跳过json文件的第一行和最后一行作为有效的json输出?

我的文件如下:

while(true);/* 0;
JSON CODE
/* */

我的php代码如下所示:

$json = file_get_contents('https://..../getLiveSchedule.json');
var_dump(json_decode($json, true));`

1 个答案:

答案 0 :(得分:1)

我遇到的问题不仅与第一行和最后一行有关。似乎我的PHP.ini文件不允许“file_get_contents”的外部URL。该脚本返回NULL作为值。解决方案是使用cURL,如下所示:

function file_get_contents_curl($url) {
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);       

    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}

$str = file_get_contents_curl('https://..../getLiveSchedule.json');

然后我可以删除前17个和后5个字符以使文件“JSON友好”:

$validJSON = substr($str, 17, -5);

输出现在是有效的JSON代码。