Reputation: 423
I have a large json object (174MB) https://www.dropbox.com/s/q3dpubc2emwrnyq/attributes-nodp.json?dl=0
I want to save the json object as decoded associative PHP array in a file for later reference/inclusion.
<?php $json_data = file_get_contents('attributes-nodp.json'); //This will retrieve your json data as a string
$arr = json_decode($json_data, true); //This will decode your string data into a PHP array; the true parameter makes it an associative array
$file = fopen("/home/kalugi/public_html/wp-content/uploads/wpallimport/files/test/raw_attributes.php", "w");
//This will open a new file raw_attributes.php for writing
//This will write and close the file
fwrite($file , $arr->__toString());
fclose($file );
?>
However this throws an error
[23-Dec-2019 12:59:46 UTC] PHP Fatal error: Uncaught Error: Call to a member function __toString() on array in /home/kalugi/public_html/wp-content/uploads/wpallimport/files/test/write-array-to-file.php:8
Stack trace:
#0 {main}
thrown in /home/kalugi/public_html/wp-content/uploads/wpallimport/files/test/write-array-to-file.php on line 8
I then tried var_export
to create a string that could be saved to the file and that didn't produce a file with anything.
<?php
$json_data = file_get_contents('attributes-nodp.json'); //This will retrieve your json data as a string
$arr = var_export(json_decode($json_data, true)); //This will decode your string data into a PHP array; the true parameter makes it an associative array
$file = fopen("/home/kalugi/public_html/wp-content/uploads/wpallimport/files/test/raw_attributes.php", "w");
//This will open a new file raw_attributes.php for writing
//This will write and close the file
fwrite($file, $arr->__toString());
fclose($file);
?>
Please advise.
Upvotes: 2
Views: 1075
Reputation: 166
It doesn't work because you're trying to invoke a __toString method on something that is not an object that has a __toString method (its an assoc. array).
If you want to save the var_export output of your data, then you have to pass true
as a second parameter(to return the data instead of echoing it):
file_put_contents(PATH_TO_FILE, var_export(json_decode($json_data,true),true));
If you want to save the actual data for future use then it IMO it would be best to either parse the file and save it to a database or just save the JSON file and use that.
Upvotes: 2