I have one large plain text file which its data is like this:
65781>foo-98503>bar-12783>baz-71284>foobar
I want to convert it to JSON format so the content should be a valid JSON:
{
"65781":"foo",
"98503":"bar",
"12783":"baz",
"71284":"foobar"
}
Because I could not find any tools on the internet that would do this for me properly, I didn't know what to do. I decided to write a PHP function to convert my file. Here is my code:
<?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")
?>
Then, I receive this error:
Fatal Error: Out of memory (allocated number) (tried to allocate another number bytes) in script.php
I tried to add this line in the top of my code, but it's not solving my problem:
ini_set('memory_limit', '2048M');
I have also changed this line in my php.ini
file:
; Maximum amount of memory a script may consume
; http://php.net/memory-limit
memory_limit=2048M
Any helps here?