1

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

1
  • Probably, not every row in your spreadsheet has a JSON-object in it with a "nome" property. If you put the echo outside the foreach, you're only looking at the last row. Commented Aug 2, 2022 at 19:07

1 Answer 1

2

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.

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

1 Comment

oooh my god, that is exactly right... i knew i was missing something, there is 1 row that doesn't has a valid JSON.... thank you very much for your answer!!

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.