写入文件时出现ArrayArray而非正常JSON输出,如何修复?
问题解决:file_put_contents写入JSON内容显示为ArrayArray的问题
问题描述
现有以下简化后的PHP方法:
function somefunction($data){ $somestuff = createMyGeojson($data) write_aa_winter_sports_points_to_file($geojson); return $geojson; } function write_aa_winter_sports_points_to_file($content){ $file = "aa_winter_sports_points.geojson"; $dir = get_template_directory() .'/fs_data/aa_winter_sports_points/override_file_for_upload/'; file_put_contents($dir.$file, $content); }
执行return $geojson时能在屏幕显示格式正确的JSON,但写入文件后内容显示为ArrayArray,尝试过print_r()无效,当前文件内容为FeatureCollectionaa_winter_sports_pointsArrayArray,需实现将屏幕显示的正确JSON内容保存到文件。
问题原因
- 变量名错误:
createMyGeojson($data)的结果赋值给了$somestuff,但后续调用写入函数时使用的是未定义的$geojson变量,实际传递的可能是上下文的其他数组变量。 - 类型不匹配:
createMyGeojson返回的是PHP数组,PHP直接将数组作为字符串写入文件时,会被强制转换为Array字符串;而框架处理return $geojson时自动完成了数组到JSON字符串的转换,因此屏幕显示正常。
解决步骤
1. 修正变量赋值错误
将变量赋值语句修正为对应变量,并补上缺失的分号:
$geojson = createMyGeojson($data);
2. 将数组转为JSON字符串后写入文件
可以选择在调用写入函数前处理,或在写入函数内部统一处理:
方案一:调用时处理(匹配屏幕显示格式)
function somefunction($data){ $geojson = createMyGeojson($data); // 转为带缩进的格式化JSON,和屏幕显示格式一致 $jsonContent = json_encode($geojson, JSON_PRETTY_PRINT); write_aa_winter_sports_points_to_file($jsonContent); return $geojson; }
方案二:写入函数内部处理(兼容数组/字符串输入)
function write_aa_winter_sports_points_to_file($content){ $file = "aa_winter_sports_points.geojson"; $dir = get_template_directory() .'/fs_data/aa_winter_sports_points/override_file_for_upload/'; // 判断输入为数组时,自动转为JSON字符串 if(is_array($content)){ $content = json_encode($content, JSON_PRETTY_PRINT); } file_put_contents($dir.$file, $content); }
补充说明
JSON_PRETTY_PRINT参数用于生成格式化的JSON,若不需要格式化可直接去掉该参数,生成紧凑格式的JSON。- 需确保
createMyGeojson返回的是合法的PHP数组结构,这样json_encode才能生成正确的JSON内容。
内容的提问来源于stack exchange,提问作者spreaderman
相关产品推荐
相关产品推荐

