James
James

Reputation: 23

PHP API saving JSON to file, then reading the file

Having trouble with this.

Basically, I'm trying to access an API to retrieve data. I'm limited to a certain number of connects, so my plan was to retrieve the data, save it to a text file on my host, and then read from that file as much as I want. I'd then use a cron job to re-populate the file with new data every few hours.

Anyway, I've logged into the API and retreived the data and can display the data "live" without an issue.

The trouble starts when trying to save the data and read from the text file. It's a multi-depth array.

The retreiving code

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, 'URL GOES HERE');
//prepare the field values being posted to the service
$data = array("appkey" => "KEY","account" => "ACCOUNT" );
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

//make the request
$result = curl_exec($ch);
curl_close($ch);

This gets the code fine, and I can display

$properties = json_decode($result, true);
$properties = $properties['properties'];
//pr($parsed_json);

foreach($properties as $key => $value) {

    if ($_GET[section] == "sale") {

        if ($value['category_id'] == "1") {

            displayProp ($address, $value['price'], $value['qualifier_name'], $value['summary']); 

        }

    } elseif ($_GET[section] == "rent") {

        if ($value['category_id'] == "2") {

            displayProp ($address, $value['price'], $value['freq_name'], $value['summary']); 

        }
    }
}

and this works.

I then try and save the json to a text file with

file_put_contents('properties.txt', json_decode($result));

which saves the data in the file okay. But when trying to read from it, I get random errors no matter what I try. Could someone help with reading the text file and outputting the array?

With JSONLint I validate the data and get the following error

Parse error on line 1:
"{    \"status\": \
^
Expecting '{', '['

Any ideas?

Upvotes: 2

Views: 4399

Answers (3)

Marc B
Marc B

Reputation: 360602

json_decode() is going to return an array or object (generally speaking). You can't just write that array/object out to a file. Writing an array in string context will just give you the literal word Array.

Why not just write out the raw JSON text?

file_put_contents('cache.json', file_get_contents($url));

and then

$data = json_decode(file_get_contents('cache.json'));

You'll spend a bit of cpu time doing the decoding each time, but at least you'll get the real data, and not a corrupted Array or whatever.

Upvotes: 3

Andy Jones
Andy Jones

Reputation: 6275

If you need to json_decode the result and work with the result, you'll want to serialize and unserialize the data.

One way to save...

file_put_contents('properties.txt', serialize(json_decode($result)));

Load...

$result = unserialize(file_get_contents('properties.txt'));

This will ensure that the data structures as preserved correctly from run to run. When storing as JSON, whether JSON objects are PHP objects vs associated arrays is unclear unless specified. serialize does not have this issue.

Upvotes: 0

elixenide
elixenide

Reputation: 44833

Ditch the json_decode - just save and read the raw JSON.

Upvotes: 3

Related Questions