2017-10-10 65 views
0

我正在製作一次性,單一用途的CSV格式轉換腳本。我從一個提供者處獲取文件,並將其字段映射到另一個提供者的格式。fgetcsv輸出不出現

到目前爲止,我有我想通過一個PHP腳本,將 1.去掉標題行 2.將CSV數據到一個數組 3.打印第一的內容運行CSV文件數組中的字段(這樣我就可以看到它的工作)

CSV文件看起來是這樣的例子:

Order Date (UTC Time Zone),Order Number,Customer Name,Customer Address,Customer Address2,City,State,Zip,Country,Product Name,Quantity,UPC,SKU,Shipping Carrier,Tracking Number 
2017-10-09,1000-000001-000001,John Doe,1234 ANY DR,"",ANY CITY,CA,90210,US,ACME® Product,1,,,"","" 

的問題是,我的腳本,下面,打印出什麼。我只想驗證我有一個數組,並且它所包含的數據正在登錄到正確的數組索引中。

<?php 
// Remove headers from the first line of file "yyyymmdd.csv" and save it to an outfile named "yyyymmdd_clean.csv" 
ini_set('auto_detect_line_endings', true); 
$original = fopen("20171010.csv", "r"); 
$first = fgets($original,2048); #get first line. 
$outfile="20171010_clean.csv"; 
$o = fopen($outfile,"w"); 
while (!feof($original)) { 
    $buffer = fgets($original,2048); 
    // Save outfile 
    fwrite($o,$buffer); 
} 
// Close original file, but don't close outfile 
fclose($original); 

// Convert cleaned outfile into array of SourceLine[n],SourceField[n] 
while (($data = fgetcsv($o)) !== FALSE) { 
    echo "OrderID " . $data[0]; 
} 
// Now close the outfile. We're done. 
fclose($o); 
?> 

我在遠程開發服務器上運行它。

我需要更改哪些內容才能將數據的第一個字段回顯到屏幕?

+1

您需要[rewind()](http://www.php.net/manual/en/function.rewind.php)輸出文件指針,因爲它位於文件末尾 –

+1

您也是以「只寫」模式打開,而不是「讀/寫」模式;你需要''w +'',而不是簡單''w「' –

+0

謝謝。那是我錯過的。 –

回答

0

由於Mark Baker聲明,問題是我沒有使用rewind(),我沒有打開它在讀/寫模式(w+)。