2

I have JSON Object which I have encoded like so

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

I am taking this JSON data and storing it in a file like so

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

which looks something like this in the file

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

Now I am reading it back form the second line like so

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

The problem is when I want to decode it back it doesn't happen,this is how I am trying to do that,

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

$a = json_decode($lines);

Now according to expected output the $a should have the decoded data but it has null.

Can someone point out the mistake?

Usama Rehan
  • 175
  • 4
  • 16

4 Answers4

3

I believe the issue is the semicolon at the end of the JSON you've read back in from the file. Try chopping that off before attempting json_decode:

$a = json_decode(rtrim($lines, ";"));
user94559
  • 59,196
  • 6
  • 103
  • 103
2

pass the second parameter true for recursively decoding

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

check the php mannual here json_decode

RAUSHAN KUMAR
  • 5,846
  • 4
  • 34
  • 70
1

It will be

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

See the post Parsing JSON file with PHP

Suraj Khanra
  • 480
  • 1
  • 5
  • 23
1

try to save data in file like

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

instead of

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

//and read like

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

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

//Print data
print_r($json_data);
Suraj Khanra
  • 480
  • 1
  • 5
  • 23