3

I'm planning to save a returned object to a file, for downloading later on to review. For clarity sake, I'm working with an outside API service, and gathering their data, for parsing into another database.

Here's what I have:

<?php
require('class.php');
$client = new connect2Them();
$logged_in = $client->login();
if(!$logged_in){
  echo "Not connected!"; die();
}

$records = $client->get_records();
if(count($records < 1){
  echo "No records found"; die();
}

$singlerecord = $records[0];
print_r($singlerecord);

?>

The print_r() works fine, and I get back a very very large amount of data. I'm doing all this via command-line, so I want to save it to a text file.

I've added this below my $singlerecord:

<?php
$myFile = "reviewLater.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $singlerecord;
fwrite($fh, $stringData);
fclose($fh);

?>

I get this error from PHP: PHP Warning: fwrite() expects parameter 2 to be string, object given in....

How do I put the print_r() into the reviewLater.txt?

1
  • Are you trying to store the data for later programmatic use, or just for human reading? Commented Nov 6, 2012 at 21:33

4 Answers 4

6

Objects can be serialized with PHP's serialize() function and saved to a file. Later you can unserialize() them to use them again if you want.

$stringData = serialize($singlerecord);

Fun Fact: This is one way to cache objects to files.

Ref: http://php.net/manual/en/function.serialize.php

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

2 Comments

Well there is var_export.
There is actually many ways to do this, and it all depends on the use case. Thanks, for adding that to the answer.
4

As said above, you can serialize(), but to answer your question:

How do I put the print_r() into the reviewLater.txt?

If you set the second parameter of print_r() to true, there will be a string of the output and you can manipulate it as such :)

1 Comment

this is exactly what I was looking for. And yet so simple
0

If you're dealing with simple objects (eg. not objects that reference themselves or are custom classes), you can use json_encode to encode the object to a JSON and json_decode to decode it later.

See http://php.net/manual/en/function.json-encode.php and http://www.php.net/manual/en/function.json-decode.php.

Comments

0

Since The question about a means to serialize the data for later programmatic use has been given, I will mention that if you are just concerned about human-readable output, you can use fwrite($fh, var_export($singlerecord, true)); to print human readable representation as string output.

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.