【发布时间】:2021-12-20 17:39:26
【问题描述】:
我有一个大的纯文本文件,它的数据是这样的:
65781>foo-98503>bar-12783>baz-71284>foobar
我想将其转换为 JSON 格式,因此内容应该是有效的 JSON:
{
"65781":"foo",
"98503":"bar",
"12783":"baz",
"71284":"foobar"
}
因为我在互联网上找不到任何可以为我正确执行此操作的工具,所以我不知道该怎么做。我决定编写一个 PHP 函数来转换我的文件。这是我的代码:
<?php
function txt_to_json_converter($sep1, $sep2, $input_file, $output_file) {
$data = file_get_contents($input_file) or die("Unable to open file...");
$exploded = explode($sep1, $data);
$array = array();
foreach ($exploded as $item) {
$pair = explode($sep2, $item);
$array[$pair[0]] = $pair[1];
}
$j = json_encode($array);
// save to disk
$myfile = fopen($output_file, "w") or die("Unable to open file...");
fwrite($myfile, $j);
fclose($myfile);
echo 'Done!';
}
txt_to_json_converter("-", ">", "my_exported_data.txt", "structured_data.json")
?>
然后,我收到此错误:
Fatal Error: Out of memory (allocated number) (tried to allocate another number bytes) in script.php
我试图在我的代码顶部添加这一行,但这并没有解决我的问题:
ini_set('memory_limit', '2048M');
我还在我的php.ini 文件中更改了这一行:
; Maximum amount of memory a script may consume
; http://php.net/memory-limit
memory_limit=2048M
这里有什么帮助吗?
【问题讨论】:
-
为什么要从错误消息中删除相关数字,您的内存使用情况是公司机密吗?这些号码本可以让我们了解您的问题
-
@RiggsFolly 不,我的内存使用量不是公司机密。我实际上删除了它,因为它不是一个常数,并且在每个程序运行中都在变化。
-
还是有用的
标签: php json converters txt