Search code examples
phpjsondatatablesphp-5.3php-7

script works in php 7 but not php 5


This code works in php 7 (localhost) but not php 5 (isp). It converts a delimited text file to a json file for use with dataTables.

source:

 6590|07/19/2003|RCC Sat. Open|C11|Nikolayev, Igor (FM)|2402|Gonzalez, Jose|2131|1-0|

Desired result:

 {"data":[
 {"game":"6624","Date":"11/01/2003","Event":"RCC Sat. Open","ECO":"C65","White":"Liman, Christ","WhiteElo":"1729","Black":"Nikolayev, Igor (FM)","BlackElo":"2408","Result":"0-1"},
....
]}

How come?

<?php

$text = file('games.txt'); $count = count($text); arsort($text);

$X = 0;

$fp = fopen("games.json", "w");

fwrite ($fp, "{"); fwrite ($fp, '"data":['); 

foreach($text as $line) {$token = explode("|", $line); 

$game = $token[0]; $date = $token[1]; $event = $token[2]; $eco = $token[3]; $white = $token[4];
$white_rating = $token[5]; $black = $token[6]; $black_rating = $token[7]; $result = $token[8];

  fwrite ($fp, "\n");
  fwrite ($fp,'{');  

  fwrite ($fp, '"game":"'.$game.'",'); 
  fwrite ($fp, '"Date":"'.$date.'",'); 
  fwrite ($fp, '"Event":"'.$event.'",'); 
  fwrite ($fp, '"ECO":"'.$eco.'",'); 
  fwrite ($fp, '"White":"'.$white.'",'); 
  fwrite ($fp, '"WhiteElo":"'.$white_rating.'",'); 
  fwrite ($fp, '"Black":"'.$black.'",'); 
  fwrite ($fp, '"BlackElo":"'.$black_rating.'",'); 
  fwrite ($fp, '"Result":"'.$result.'"'); 

  $X++;

  fwrite ($fp, '}');
  if ( $X <= $count-1 ) {fwrite ($fp, ',');}

  }

  fwrite ($fp, "]"); 

  fwrite ($fp, "}"); 

  fclose($fp);

  header('Location:pgn_assistant.php');
  ?>

Solution

  • using the PHP Documentation you can use json_encode

    It is native way to encode an array or any object implementing \JsonSerializable into json string.

    file_put_contents('myfile.json', json_encode($data));