Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Read from CSV File and Write that data in different format in txt file in PHP

I am reading from csv file and writing the data in txt file using the code below:

$row = 1;
$file = fopen("newfile.txt","w");

if (($handle = fopen("Last.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        $row++;
        $colOne = rtrim($data[0],"'");
        echo $colOne . "\n" . $data[3] . "<br />\n";
       
        $line = $colOne."_".$data[3];
        $line .=  "\n";
        fputs($file, $line);
    }
    fclose($handle);
}
fclose($file);

The fields required in the text files are obtained as needed. But I want to have a format from '000065 2022-06-01 08:06:38 to 000065_2022-06-01_08:06:38. I have tried the methods like using pre_replace(), rtrim() but was not able to achieve the desired result.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use ltrim() to remove the quote from the beginning.

Use str_replace() to replace the spaces with underscores.

$colOne = str_replace(' ', '_', ltrim($data[0], "'"));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading