2

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?

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

when doing that the json is displayed perfectly in the text file but when getting the data and arrays I get Warning: Illegal string offset 'properties' in /var/sites/s/steve-morris1.co.uk/public_html/new/inc/properties.php on line 27 Warning: Invalid argument supplied for foreach() in /var/sites/s/steve-morris1.co.uk/public_html/new/inc/properties.php on line 43
That's because you are trying to loop over the raw data. You need to read it, then do json_decode on the raw data before you can loop over it in PHP.
3

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.

Comments

0

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.

3 Comments

Trying this I get - Warning: json_decode() expects parameter 1 to be string, object given in /var/sites/s/steve-morris1.co.uk/public_html/new/inc/properties.php on line 26 Warning: Invalid argument supplied for foreach() in /var/sites/s/steve-morris1.co.uk/public_html/new/inc/properties.php on line 44
Why mix serializations here unnecessarily? Just extra overhead. There is absolutely NO ambiguity in how PHP treats JSON-encoded data with regards to objects vs. associative arrays, as there is no such thing as an associative array construct in JSON. The ambiguity exists when developers want to use the json_decode() option to force associative arrays and don't do it consistently. Without delving into this option PHP will only deserialize JSON into objects and numerically indexed arrays. In this case especially, all you are trying to do is make a local copy of the JSON file why change it?
Warning: Invalid argument supplied for foreach() in /var/sites/s/steve-morris1.co.uk/public_html/new/inc/properties.php on line 44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.