Reputation: 97
I'm trying to write a a text file using sql query but it shows an error saying:
Object of class stdClass could not be converted to string
Here is my code:
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$ss=DB::select("SELECT commercial_library FROM tbl_schedule");
$stringData = implode(', ',$ss);
fwrite($myfile, $stringData);
fclose($myfile);
Upvotes: 0
Views: 1688
Reputation: 422
You get Object of class stdClass could not be converted to string
after converting $ss
to array because you have still an array of objects. I tried to solve your problem using recursive function. I have both stdClasses and values on different levels. Please, replace my definition of $ss
with your query and try my code.
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$ss = new stdClass();
$ss->a = new stdClass();
$ss->a->a = new stdClass();
$ss->a->b = new stdClass();
$ss->b = new stdClass();
$ss->a->a->a = "!";
$ss->a->a->b = "T";
$ss->a->b->a = "E";
$ss->a->b->b = "X";
$ss->b->a = "T";
$ss->b->c = 1;
$string = recursive($ss, "");
fwrite($myfile, $string);
fclose($myfile);
function recursive($objects, $string) {
foreach($objects as $object) {
if ($object instanceof stdClass) {
$string = recursive((array) $object, $string);
} else {
$string .= implode(', ', (array) $object); //my example is to concatenate
}
}
return $string;
}
Upvotes: 1
Reputation: 778
Convert object in to array and then use implode. Implode takes first arguments as array.
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$ss=DB::select("SELECT commercial_library FROM tbl_schedule");
$ss = (array) $ss;
$stringData = implode(', ', $ss);
fwrite($myfile, $stringData);
fclose($myfile);
Upvotes: 1
Reputation: 83
Implode converts an array to a string. I dont think $ss
is an array in your case, it looks like an object. That might be the reason you are getting this error.
Upvotes: 1