0

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);
3
  • implode works on arrays, you have used it on an object Commented May 24, 2017 at 20:33
  • Seems like DB select returns object and you are trying to do implode with object. You need array to do implode. Convert your object in to array and then use implode. Commented May 24, 2017 at 20:36
  • when i remove the error i get this fwrite() expects parameter 2 to be string, array given Commented May 25, 2017 at 1:21

3 Answers 3

1

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.

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

1 Comment

when i remove the error i get this fwrite() expects parameter 2 to be string, array given
1

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);

1 Comment

Object of class stdClass could not be converted to string still getting this error
1

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;
}

Comments

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.