2017-01-30 5 views
0

이 코드는 php 7 (localhost)에서 작동하지만 php 5 (isp)에서 작동하지 않습니다. 구분 된 텍스트 파일을 dataTables과 함께 사용하기 위해 json 파일로 변환합니다.스크립트는 PHP 7에서 작동하지만 PHP 5는 작동하지 않습니다.

소스 :

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

'json_encode'가 기본적으로 존재할 때 고유 한 JSON 변환 방법을 만드는 것은 좋지 않습니다. 또한 오류가 있습니까? – apokryfos

+0

오류가 발생하지 않습니다. 조만간 json_encode를 조사하겠습니다. – verlager

+0

PHP 5.6과 호환되지 않는 것은 보이지 않습니다. 읽고 쓰려고하는 파일에 대한 사용 권한이 맞습니까? 또는 올바른 위치에 있습니까? – thodic

답변

2

사용할 수있는 PHP 문서를 사용하여 json_encode

이 배열 또는 JSON 문자열로 \JsonSerializable를 구현하는 모든 객체를 인코딩하는 기본 방법입니다.

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