我有一個大的純文本檔案,它的資料是這樣的:
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
這里有什么幫助嗎?
uj5u.com熱心網友回復:
首先,呼叫該php_info()函式并檢查memory_limit該值是否設定正確。
如果未設定,請確保在此更改后重新啟動 Apache。然后檢查沒有其他
php.ini檔案覆寫主檔案php.ini
另外,確保檔案中php_value memory_limit xxxM沒有設定標志.htaccess。如果設定了,嘗試增加這個值,例如4096M或更大,重啟Apache后,再次測驗你的功能。
你說你寫這個函式是出于需要?
許多在線工具會為您執行此操作并挽救您的生命。我測驗了Vertopal - TXT 到 JSON并在設定中設定分隔符。結果令人滿意。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/353748.html
上一篇:Python扁平化深嵌套JSON
