2016-07-19 11 views
2

私はfile_get_contentsでjsonファイルを読んだ後にissuseを持っています。PHP:json_decodeが一緒に機能していないfile_get_contents

私は、その作業OK、このコードを実行すると:

<?php 
$json='[ 
    { 
    "fullName":"Shachar Ganot", 
    "address":"Yad Rambam", 
    "phoneNumber":"050-1231233", 
    "email":"", 
    "note":"", 
    "role":"", 
    "area":"" 
    }, 
    { 
    "fullName":"Betty Ganot", 
    "address":"Modiin", 
    "phoneNumber":"054-3213211", 
    "email":"", 
    "note":"", 
    "role":"", 
    "area":"" 
    }, 
    { 
    "fullName":"Someone Else", 
    "address":"Somewhere", 
    "phoneNumber":"123456789", 
    "email":"", 
    "note":"", 
    "role":"", 
    "area":"" 
    } 
]'; 

//$json = file_get_contents('Test.txt'); 
$data = json_decode($json,true); 
echo $data[0]['fullName']; 

?> 

結果: Shachar Ganot

私は、その空にこのコードを実行すると:

<?php 
$json = file_get_contents('Test.txt'); 
$data = json_decode($json,true); 
echo $data[0]['fullName']; 

?> 

の検索結果を: ****空 - Nothigが表示されます****

私はこのコードを実行し、のfile_get_contentsが動作しているかどうかを確認するには:

<?php 
$json = file_get_contents('Test.txt'); 
$data = json_decode($json,true); 
echo $json; 

?> 

結果:

[{ "のfullName": "Shachar Ganot"、 "住所": "ヤドRambam" を、 "phoneNumber": "050-1231233"、 "email": ""、 "note": ""、 "role": ""、 "area": ""}、{"fullName": "Betty Ganot" 「住所」:「Modiin」、「phoneNumber」:「054-3213211」、「email」:「」、「note」:「」、「role」:「」、「area」:「」}、{"fullName" : ""、 "住所": "どこか"、 "phoneNumber": "123456789"、 "email": ""、 "note": ""、 "role": ""、 "area": ""} ]


私は行方不明ですか?あなたがTest.txtがUTF-8(with BOM)でエンコードされている場合は

言うまでもないが、私はhttps://jsonformatter.curiousconcept.com/

答えて

5

で有効なJSONをしたと言って、json_decode関数が失敗するとNULLを返します。

あなたは、ファイルの内容を固定することによってこの問題を解決する、またはあなたの$json文字列からBOMをトリミングすることができます

$json = trim(file_get_contents('Test.txt'), "\xEF\xBB\xBF"); 
$data = json_decode($json,true); 
echo $data[0]['fullName']; 

ファイルの内容が正しいことを確認するために非常に良くなるとあなたが本当にしなければ、トリム機能を使用しないでください。

たとえば、を使用して、コンテンツをUTF-8からBOMで、BOMなしでUTF-8に変更することができます。

+0

thats正常に動作します。ありがとう(: – Shachar87

関連する問題