Object of class stdclass could not be converted to string – What’s going on?

When you work with PHP, have you ever got the error Object of class stdclass could not be converted to string? If yes, don’t worry about that. 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 the array with the 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. That occurs because $data is an array, but it’s made up of objects. So, in order to solve this issue successfully, it’s necessary for you to convert its content to the array before you generate it. Let’s dive in 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 of PHP function. Stdclass should return an array, not a single object. So, here is the method to address the error with the specific 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 for you to ensure that Stdclass should return the array instead of single objects. If your content is objects, you need to convert it into the 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 your comment below so that 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.

5/5 - (2 votes)
Lt Digital Team (Content &Amp; Marketing)
Latest posts by LT Digital Team (Content & Marketing) (see all)

Flash Sale! Get 25% Off for everything on today, don't miss it. Coupon code: FSALE25 Redeem Now
Flash Sale! Get 25% Off for everything on today, don't miss it. Coupon code: FSALE25 Redeem Now