0

I am using PHP and converting the JSON data into the CSV format and later on read the same CSV file for further processing.

Below is my code that converts the JSON data in to the CSV format.

function LoadDataFromFile($file)
{

$json = file_get_contents($file);
$array = json_decode($json, true);
$f = fopen('out.csv', 'w');
$firstLineKeys = false;
$keys = array();
//first collect keys
foreach($array as $line){
    foreach($line as $key => $value){
        if(!in_array($key, $keys))
            $keys[] = $key;
    }
}
$keyString = implode(",", $keys);
fwrite($f, "$keyString\n");
foreach ($array as $line)
{
    $outputArray = array();
    foreach($keys as $key){
        if(array_key_exists($key, $line)){
            $outputArray[] = str_replace(',', '', $line[$key]);;
        } else {
            $outputArray[] = "";
        }
    }
    $outputString = implode(",", $outputArray);
    fwrite($f, "$outputString\n");
}
fclose($f);

}

As we can see that, i am writing data into the "out.csv" file, and later on i am reading same CSV file and assign the value/ full contents of the same file line by line to $array variable, as shown below.

$array = explode("\n", file_get_contents('out.csv'));

Now, I want to directly assign the value of csv contents into the $array variable with out using the intermediate "out.csv" file.

Wondering what data structure should i use while converting JSON data to CSV format, and possible code changes required for "LoadDataFromFile" method?

2
  • Is your JSON always has the same format? Commented May 24, 2019 at 1:46
  • If yes please provide your json Commented May 24, 2019 at 1:52

1 Answer 1

1

If you can already convert the json into csv, then just append the output strings together assigned to a string variable instead of writing it to a file. Or am I misunderstanding what you want?

Instead of:

fwrite($f, "$outputString\n");

you can put:

$csv .= $outputString;

And finish it with:

$array = explode("\n", $csv);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks It worked. $csv .= $outputString; $csv .="\n";

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.