我有一个很大的json对象(174MB) https://www.dropbox.com/s/q3dpubc2emwrnyq/attributes-nodp.json?dl=0
我想将json对象作为解码后的关联PHP数组保存在一个文件中,供以后引用/包含。
<?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 );
?>但是,这会抛出一个错误
[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然后,我尝试使用var_export创建一个可以保存到文件中的字符串,但没有生成包含任何内容的文件。
<?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);
?>请给我建议。
发布于 2019-12-23 23:00:51
它不起作用是因为您试图在不是具有__toString方法的对象上调用__toString方法(它是一个assoc。数组)。
如果要保存数据的var_export输出,则必须将true作为第二个参数传递(以返回数据,而不是回显数据):
file_put_contents(PATH_TO_FILE, var_export(json_decode($json_data,true),true));如果您想保存实际数据以供将来使用,那么最好是解析文件并将其保存到数据库中,或者只保存JSON文件并使用它。
https://stackoverflow.com/questions/59455889
复制相似问题