首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将json对象另存为文件中已解码的PHP数组

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

Stack Overflow用户
提问于 2019-12-23 21:06:54
回答 1查看 235关注 0票数 2

我有一个很大的json对象(174MB) https://www.dropbox.com/s/q3dpubc2emwrnyq/attributes-nodp.json?dl=0

我想将json对象作为解码后的关联PHP数组保存在一个文件中,供以后引用/包含。

代码语言:javascript
运行
复制
<?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 );
?>

但是,这会抛出一个错误

代码语言:javascript
运行
复制
[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创建一个可以保存到文件中的字符串,但没有生成包含任何内容的文件。

代码语言:javascript
运行
复制
<?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);
?>

请给我建议。

EN

Stack Overflow用户

发布于 2019-12-23 23:00:51

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

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

代码语言:javascript
运行
复制
file_put_contents(PATH_TO_FILE, var_export(json_decode($json_data,true),true));

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

票数 2
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59455889

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档