Reputation: 13120
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?
Upvotes: 3
Views: 15606
Reputation: 71384
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.
Upvotes: 0
Reputation: 5443
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.
Upvotes: 0
Reputation: 1943
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 :)
Upvotes: 4
Reputation: 24549
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
Upvotes: 6