简体   繁体   中英

How do I make sure a CSV file contains data before parsing it?

I have a PHP file where I attempt to open a CSV file, parse the data into XML format, then save the XML file. I ran into a challenge with making sure the CSV file actually has the data I am looking for before parsing anything.

The CSV file will be updated daily with new information and the PHP script will be executed daily to update the XML file.

I attempted to use the fgetcsv() PHP function to check if the the returned array is greater than 1, but this only checks a single line from the CSV. I am not sure this is the best method to use.

if (($file = fopen('employees.csv', "r")) !== FALSE) {

            if (fgetcsv($file, 1000, ",") > 1) {
                $dom = new DOMDocument();
                $dom->encoding = 'utf-8';
                $dom->xmlVersion = '1.0';
                $dom->formatOutput = true;
                $root = $dom->createElement('employees');

                while (($data = fgetcsv($file, 1000, ",")) !== FALSE) {
                    $emp_node = $dom->createElement('employee');

                    $faculty = 'F';
                                        ...   

I expect to get a saved XML file containing all data parsed from the employees.csv file. If for any reason, the CSV file is overwritten with no data (empty CSV), I do not want the PHP script to overwrite the XML file.

You should not overwrite your file directly but create new temporary one, write parsed data to it, then delete old file and rename temp file to expected name IF and ONLY IF parsing went well.

Checking size etc is naive - there are tons of other things that may go wrong, incl. malformed CSV content in mid-file etc. In your approach in case of troubles you would end up with no valid file, while going suggested way you still have at least last valid file in hand, like nothing wrong happened. You should simply always assume parsing went wrong unless you are sure otherwise (by any criteria of choice).

I would do something like this:

<?php

$content = file_get_contents('employees.csv');
if (!empty($content))
{
   $lines = explode("\n", $content);
   foreach ($lines as $line)
   {
       // $line = 1 line
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM