Object of class stdclass could not be converted to string – What’s going on?
When you work with PHP, have you ever gotten the error Object of class stdclass could not be converted to string? If so, don’t worry. We are here today to help you find the best solution for this error. Now, let’s have a look at the following example:
You create an Excel file from an array with this code:
//$results is taken with db query
$data = array();
foreach ($results as $result) {
$result->filed1 = 'some modification';
$result->filed2 = 'some modification2';
$data[] = $result;
}
Excel::create('Filename', function($excel) use($data) {
$excel->sheet('Sheetname', function($sheet) use($data) {
$sheet->fromArray($data);
});
})->export('xls');
However, the error Object of class stdclass could not be converted to string appears. This happens because $data is an array, but it’s made up of objects. So, in order to solve this issue successfully, you need to convert its content to an array before you generate the file. Let’s dive into the solution for this example in the next part now!
How to fix Object of class stdclass could not be converted to string?
As we mentioned above, the Object of class stdclass could not be converted to string is an error from a PHP function. Stdclass should return an array, not a single object. So, here is how to fix the error in the example above:
$data = array();
foreach ($results as $result) {
$result->filed1 = 'some modification';
$result->filed2 = 'some modification2';
$data[] = (array)$result;
#or first convert it and then change its properties using
#an array syntax, it's up to you
}
Final words
Simply put, it’s important to ensure that Stdclass returns an array instead of single objects. If your content consists of objects, you need to convert it into an array to avoid the error Object of class stdclass could not be converted to string.
If you have any questions about that, don’t hesitate to leave a comment below and we will reply to you as soon as possible. Last but not least, don’t forget to visit our site and get many responsive free WordPress themes and Joomla 4 Templates. Thank you and see you again.



