2017-06-06 24 views
2

工作,我有我有编码的,像这样json_decode不会对我的字符串

{ 
"id": "", 
"steps": [ 
      { 
     "target": "purchase_order_items_itemmaster_id", 
     "title": "", 
     "placement": "", 
     "content": "", 
     "xoffset": "", 
     "yoffset": "" 
       } 
     ] 
} 
$JSONData = json_encode($finalData,JSON_PRETTY_PRINT); 

我借此JSON数据并将其存储在一个文件中,像这样

File::put("path","var tour = \n [ \n\t $JSONData \n ];"); 

JSON对象,看起来是这样的文件

var tour = 
[ 
    { 
    "id": "", 
    "steps": [ 
     { 
      "target": "purchase_order_items_itemmaster_id", 
      "title": "", 
      "placement": "", 
      "content": "", 
      "xoffset": "", 
      "yoffset": "" 
     } 
    ] 
} 
]; 

现在,在我读回来形成像这样

0123第二线
[ 
    { 
    "id": "", 
    "steps": [ 
     { 
      "target": "purchase_order_items_itemmaster_id", 
      "title": "", 
      "placement": "", 
      "content": "", 
      "xoffset": "", 
      "yoffset": "" 
     } 
    ] 
} 
]; 

问题是,当我想它解码回到它不会发生,这就是我正在尝试的是,根据预期的输出

$lines = file_get_contents("path",NULL,NULL,10); 

$a = json_decode($lines); 

我们做一个$应该有解码的数据,但它有空。

有人能指出错误吗?

+0

HTTP ://php.net/manual/en/function.json-las t-error.php它打印什么? – varuog

回答

2

传递的第二个参数true用于递归解码

$a = json_decode(chop($lines,";"),true); 

检查PHP mannual这里json_decode

+0

已经试过,不行! –

+0

@UsamaRehan我编辑了我的答案,请试试这个 –

1

这将是

$str = file_get_contents('http://example.com/example.json/'); 
$json = json_decode($str, true); // decode the JSON into an associative array 

查看信息 Parsing JSON file with PHP

+0

已经尝试过了,不起作用! –

3

我相信这个问题是你从文件中读回来的JSON结尾的分号。尝试尝试json_decode之前砍其关闭:

$a = json_decode(rtrim($lines, ";")); 
+0

是无效的json数据可能导致json_decode失败 –

1

尝试在文件中的数据保存像

$fp = fopen('path', 'w'); 
fwrite($fp, json_encode($JSONData)); //if $JSONData is in string 
fclose($fp); 

,而不是

File::put("path","var tour = \n [ \n\t $JSONData \n ];"); 

//和念想

// Read JSON file 
$json = file_get_contents('path'); 

//Decode JSON 
$json_data = json_decode($json,true); 

//Print data 
print_r($json_data); 
相关问题