简体   繁体   English

在解析之前,如何确保CSV文件包含数据?

[英]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. 我有一个PHP文件,尝试打开CSV文件,将数据解析为XML格式,然后保存XML文件。 I ran into a challenge with making sure the CSV file actually has the data I am looking for before parsing anything. 我遇到了一个挑战,要确保CSV文件在解析任何内容之前确实具有我要查找的数据。

The CSV file will be updated daily with new information and the PHP script will be executed daily to update the XML file. CSV文件将每天使用新信息进行更新,PHP脚本将每天执行以更新XML文件。

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. 我试图使用fgetcsv() PHP函数检查返回的数组是否大于1,但这仅检查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. 我希望得到一个保存的XML文件,其中包含从employee.csv文件解析的所有数据。 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. 如果由于某种原因,CSV文件被覆盖而没有数据(空CSV),则我不希望PHP脚本覆盖XML文件。

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. 您不应直接覆盖文件,而应创建新的临时文件,向其中写入已解析的数据,然后删除旧文件并将临时文件重命名为预期名称IF,并且仅在解析顺利的情况下。

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. 中间文件等中的CSV内容格式错误。在遇到麻烦的情况下,您最终将没有有效文件,而按照建议的方式,您至少还有最后一个有效文件,就像没有发生任何错误一样。 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
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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