Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Strange behavior on json_decode in PHP code

I was just studying and messing around with PHP, when i encountered something that, to me, doesn’t make much sense, but i could be missing something.
So, i have this spreadsheet file that i load on my system, and i want to print every data that is inside the file. I load the file, and turn it into an array, like this:

$file = $request->spreadsheet;
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file);
$spreadsheet = $spreadsheet->getActiveSheet();
$data_array =  $spreadsheet->toArray();

So far so good. Now, i want to print everything that is inside this file, but i wanted to display is using it’s attributes, something like:

foreach($data_array as $data){
    $x = json_decode($data[2]); 
    echo $x->nome;
    echo $x->telefone;
}

I’m accessing $data[2] because its the third position of the array that contains all the info about the user, like name, telephone or whatever.
The thing is, if i run the code like i’ve just showed, i get the error "Trying to get property ‘nome’ of non-object", but if i try to echo the EXACT same thing, but outside the "foreach", like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

foreach($data_array as $data){
    $x = json_decode($data[2]);            
}
echo $x->nome;
echo $x->telefone;

I have no error at all, and shows me the info perfectly, so.. what is going on ? lol

>Solution :

The property of a non-object error inside the foreach means this particular row either has no JSON or is invalid JSON. Your last snippet working OK means the last row has valid JSON.

It’s possible the first row is column header, for example "Data" which of course will not parse as JSON and will trigger the error.

Look at your spreadsheet rows to narrow it down, and you can output var_dump($data[2]) in the foreach.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading