Home > other >  convert a txt data file to structured JSON using PHP
convert a txt data file to structured JSON using PHP

Time:11-08

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?

CodePudding user response:

First, call the php_info() function and check memory_limit to see if this value is set correctly or not.

  • If it was not set, make sure you restart your Apache after this change. Then check that no other php.ini file overrides the main php.ini
    Also, make sure that the php_value memory_limit xxxM flag is not set in .htaccess file.

  • If it was set, try to increase this value, for example, 4096M or more, and after restarting Apache, test your function again.

You said you wrote this function out of necessity?
Many online tools do this for you and save your life. I tested Vertopal - TXT to JSON and set your delimiters on settings. The result was satisfactory.

  • Related