我有一个大型纯文本文件,其数据如下:
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
这里有什么帮助吗?
最佳答案
首先,调用php_info()
函数并检查memory_limit
以查看该值是否设置正确。
如果未设置,请确保在更改后重新启动 Apache。然后检查是否没有其他
php.ini
文件覆盖主php.ini
另外,请确保.htaccess
文件中未设置php_value memory_limit xxxM
标志。如果设置了,请尝试增加该值,例如4096M或更多,然后重新启动Apache后,再次测试您的功能。
你说你写这个函数是出于需要?
许多在线工具可以为您做到这一点并挽救您的生命。我测试过Vertopal - TXT to JSON并在设置中设置分隔符。结果很满意。
关于php - 使用 PHP 将 txt 数据文件转换为结构化 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69874031/