-1

How can I make json_decode to skip the first and last line of a json file to be valid json output?

My file looks like this:

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

My php code looks like this:

$json = file_get_contents('https://..../getLiveSchedule.json');
var_dump(json_decode($json, true));`
user2282217
  • 91
  • 1
  • 10
  • 3
    that's not json_decode's problem. if you want to skip lines, then remove them from the json string before you pass it to the decode call. – Marc B May 12 '15 at 17:31
  • 1
    The answer can be found here http://stackoverflow.com/a/5775475/2191572 – MonkeyZeus May 12 '15 at 17:33

1 Answers1

1

The problem I had was not only related to the first and last line. It seems that my PHP.ini file wouldn't allow external url for "file_get_contents". The script returned NULL as value. The solution was to use cURL instead, like this:

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

Then I could remove the first 17 and the last 5 characters to make the file "JSON friendly":

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

The output is now valid JSON code.

user2282217
  • 91
  • 1
  • 10