JSON and PHP – pulling data from the stock exchange

mitchy asked
php arrays json

I am struggling to find a solution to a PHP/JSON issue. I have written a script that shows stock market pricing using a URL that pulls down a JSON file. I am new to PHP and I can’t seem to access the individual elements in the JSON file.

Here is my script:


$price = file_get_contents('http://data.asx.com.au/data/1/share/TLS/prices?interval=daily&count=1');
$fileprices = json_decode($price, true);
print_r ($fileprices); 

This returns :

[data] => Array (
    [0] => Array (
        [code] => FET
        [close_date] => 2017-11-06T00:00:00+1100
        [close_price] => 2.81
        [change_price] => 0.01
        [volume] => 85278
        [day_high_price] => 2.83
        [day_low_price] => 2.78
        [change_in_percent] => 0.357%

How can I access the element [code] and return the data FET or any other element?

I have tried numerous methods without success. Any help will be appreciated.


I suggest not passing the , true flag to json_decode(), which converts the whole response into an associative array for seemingly no reason. A JSON object is, by default, an object, and there’s no need to convert to an array in this case. Nothing wrong with it, but no reason either.

With that said, here’s an example showing how to use the default behavior of json_decode() to get the properties you’re looking for.

$response = file_get_contents('http://data.asx.com.au/data/1/share/TLS/prices?interval=daily&count=1');
$response = $response ? json_decode($response) : null;

if ( $response instanceof StdClass ) {
    echo $response->data[0]->code."n";
    echo $response->data[0]->close_price."n";
    echo $response->data[0]->change_price."n";
    // etc...
Share This
Posted in: