Home > Software design >  Strange behavior on json_decode in PHP code
Strange behavior on json_decode in PHP code

Time:08-03

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:

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

CodePudding user response:

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.

  • Related