使用php编辑.csv文件时苦苦挣扎

时间:2017-11-15 10:00:54

标签: php csv

我正在使用Php为学校项目创建联系人列表。我将所有联系信息存储在.csv文件中。我设法在index.php中动态显示csv文件。联系人列表中的每个人都有唯一的ID。现在我正在努力根据uniqueid编辑csv文件。 这些是我到目前为止编写的代码。

function 
edit_csv($filename, $no_rows, $id){
    $file_open = fopen($filename, 'w');
    foreach ($no_rows as $newRow){
        if($newRow[0] === $id){
            file_put_contents($filename, serialize($newRow));
        }
    }
    fclose($file_open);

}

function edit_Contact($titleEdit,$fnameEdit,$lnameEdit,$emailEdit,$websiteEdit,$cPhoneNumEdit,$hPhoneNumEdit,$oPhoneNumEdit,$twitterEdit,$facebookEdit,$commentEdit){
    $data = read_csv('contract_data.csv'); // just reads the .csv file
    $handle = fopen('ids', 'r');  // unique id stored here. 
    $id = fread($handle, filesize('ids'));
    fclose($handle);

        $data[] = array(
        'sr_no' => $id,
        'Title' => $titleEdit,
        'FirstName' => $fnameEdit,
        'LastName' => $lnameEdit,
        'email' => $emailEdit,
        'website' => $websiteEdit,
        'CellPhoneNumber' => $cPhoneNumEdit,
        'HomePhoneNumber' => $hPhoneNumEdit,
        'OfficePhoneNumber' => $oPhoneNumEdit,
        'twitter' => $twitterEdit,
        'Facebook' => $facebookEdit,
        'Comment' => $commentEdit
        );
        edit_csv('contract_data.csv', $data, $id);

        return $data;

}

1 个答案:

答案 0 :(得分:0)

如何使用fputcsv代替下面的file_put_contents,

示例代码: -

$path = "C:\\path\\to\\your\\file.csv";
if (($handle = fopen($path, "r+")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        if($data[0]==2){ //desired line to update
            $write_data = array(
                        'sr_no' => $id,
                        'Title' => $titleEdit,
                        'FirstName' => $fnameEdit,
                        'LastName' => $lnameEdit,
                        'email' => $emailEdit,
                        'website' => $websiteEdit,
                        'CellPhoneNumber' => $cPhoneNumEdit,
                        'HomePhoneNumber' => $hPhoneNumEdit,
                        'OfficePhoneNumber' => $oPhoneNumEdit,
                        'twitter' => $twitterEdit,
                        'Facebook' => $facebookEdit,
                        'Comment' => $commentEdit
                        );
            fputcsv($handle, $write_data, ',', '"');
            unset($write_data);
        }
    }
    fclose($handle);
}