脚本适用于php 7但不适用于php 5

时间:2017-01-30 12:39:10

标签: php json datatables php-5.3 php-7

此代码适用于php 7(localhost),但不适用于php 5(isp)。它会将分隔的文本文件转换为json文件,以便与dataTables一起使用。

源:

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

期望的结果:

 {"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"},
....
]}

怎么回事?

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

1 个答案:

答案 0 :(得分:2)

使用PHP文档,您可以使用json_encode

将数组或实现\JsonSerializable的任何对象编码为json字符串的本地方式。

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