0

I have created a local Json but not sure how to access this json array in php. Following is a small extract from the JSON file.

    [
      {
        "EPIC": "PRU",
        "Company Name": "Prudential PLC",
        "Market Cap": 38946.60485268,
        "Closing Price": 1498,
    "Net Change": 38.5,
    "% Change": 2.638,
    "PE": 21.7211629087218,
    "52W High": 1795,
    "52W Low": 1299.5,
    "Volume": 8465.537
  },
  {
    "EPIC": "LGEN",
    "Company Name": "Legal & General Group PLC",
    "Market Cap": 16402.72850975,
    "Closing Price": 275,
    "Net Change": 7.3,
    "% Change": 2.727,
    "PE": 8.66360027723522,
    "52W High": 292.3,
    "52W Low": 214.9,
    "Volume": 32031.848
  }
]

Could someone please advise how can I access the elements of this array.

I have tried the following code with no result:

$strJsonFileContents = file_get_contents("FileNAME.json");
// Convert to array
$array = json_decode($strJsonFileContents);
echo $array->EPIC;

I would like to extract each element of the array and present it on the website in a tabular format.

Nick
  • 138,499
  • 22
  • 57
  • 95
Vikram
  • 1
  • 1
  • 2
    Your json is an array, so access each 'record' with: `echo $array[0]->EPIC;`, for the first (PRU), or `echo $array[1]->EPIC;` (LGEN) for the second record. – lovelace Oct 21 '19 at 23:16
  • Running your code, using `$array[0]->EPIC` or `$array[1]->EPIC` works just fine, also for version 5.6 - [working demo](https://3v4l.org/Egkq1) – lovelace Oct 22 '19 at 09:36
  • @lovelace @hovhanes Thanks for taking the time out to help me. I managed to solve it. i was using code `$array = json_decode($strJsonFileContents,true);` which i changed to `$array = json_decode($strJsonFileContents);` and it worked. – Vikram Oct 22 '19 at 20:30

1 Answers1

0

The objects in your JSON object are in an array. try ... echo $array[0]->EPIC; or ... echo $array[1]->EPIC;

  • Thanks for replies @lovelace @Hovhannes. However, when i tried `echo $array[0]->EPIC;` it throws follwing error. PHP Fatal error: Uncaught Error: Cannot use object of type stdClass as array in /Applications/MAMP/htdocs/stock/JsonRead.php:5 Stack trace: #0 {main} thrown in /Applications/MAMP/htdocs/stock/JsonRead.php on line 5 – Vikram Oct 22 '19 at 08:03
  • Could you please mention the version of PHP? – Hovhannes Hayryan Oct 22 '19 at 08:14
  • @hovehanes I am using Phpstorm and it says PHP language level 5.6. I have the option to select other versions. – Vikram Oct 22 '19 at 08:47