2012-11-24 52 views
0

我有這個內容以.json文件:json_encode問題與的file_get_contents

{ "questions": "reponse" } 

而且我想該文件的內容解析爲一個PHP數組,但我有一個奇怪的問題......

$path = 'myFile.json'; 
echo file_get_contents($path); 
echo var_dump(json_decode(file_get_contents($path), true)); 
echo var_dump(json_decode(utf8_encode(file_get_contents($path), true))); 
$json = '{ "questions": "reponse" }'; 
echo var_dump(json_decode($json, true)); 

我的屏幕上的結果是:

{ "questions": "reponse" } 
null 
null 
array (size=1) 
    'questions' => string 'reponse' (length=7) 

什麼是從文件和個字符串之間的區別在我的程序中的字符串?

謝謝!

+1

文件中的尾部空白? BOM中的文件?什麼'strcmp(file_get_contents($ path),$ json)'show?另外,'var_dump(unpack('H *',file_get_contents($ path)))'show - 這應該會產生一個原始的十六進制文件內容轉儲,將其與'$ json'的轉儲進行比較,以查看區別在於。 – DCoder

+0

即使尾隨空格,這也能正確解析我。 –

+0

您使用的是哪個版本的PHP?也許這是解決方案:'echo file_get_contents($ path,FILE_USE_INCLUDE_PATH);'確保文件的路徑是正確的 –

回答

0

嘗試運行這段代碼:

var_dump(json_decode(trim(file_get_contents($path)), true)); 

我希望有一些空格(如BOM/UTF-8頭),這鬧事。

+0

確實...這是一個BOM/UTF-8標題!感謝您的幫助 – user1180339

0

utf8_encode()只需要一個參數。你通過兩個。一旦它被固定,它應該工作:

{ "questions": "reponse" } 
array(1) { 
    ["questions"]=> 
    string(7) "reponse" 
} 
object(stdClass)#1 (1) { 
    ["questions"]=> 
    string(7) "reponse" 
} 
array(1) { 
    ["questions"]=> 
    string(7) "reponse" 
} 
+0

在測試中沒有utf8_encode()的情況下,OP得到一個'null' –

+0

在修復後,它對我的​​數據有效,所以我懷疑他的「myFile.json」是罪魁禍首。物料清單可以是要查找的東西 –