繁体   English   中英

将 json 对象另存为文件中已解码的 PHP 数组

[英]Save json object as decoded PHP array in file

我有一个大的 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);
?>

请指教。

它不起作用,因为您试图在不是具有 __toString 方法的对象(它的关联数组)上调用 __toString 方法。

如果要保存数据的 var_export 输出,则必须将true作为第二个参数传递(以返回数据而不是回显数据):

file_put_contents(PATH_TO_FILE, var_export(json_decode($json_data,true),true));

如果您想保存实际数据以备将来使用,那么 IMO 最好解析文件并将其保存到数据库中,或者只保存 JSON 文件并使用它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM