[英]Export data into an existing csv file using php
我正在嘗試從數據庫中獲取數據並將其加載到現有的csv文件中,但沒有錯誤,但是每次我檢查該文件時,它仍然為空。 這是我的PHP文件:
<?
$server="XXXX";
$user="XXXX";
$password="XXXX";
$db="XXXX";
mysql_connect($server,$user,$password) or die('erreur au serveur');
mysql_select_db($db) or die('erreur db');
if ($file=fopen('XXXX/toERP/exportfactures.csv','w')!=FALSE){
$req='select * from facture';
$sql = mysql_query($req);
$cpt=1;
$response["factures"] = array();
$output=fopen('http://XXXXX/toERP/exportfactures.csv','w');
if (mysql_num_rows($sql) > 0) {
// looping through all results
// factures node
while ($row = mysql_fetch_array($sql)) {
// temp user array
$facture = array();
$facture["id_fac"] = $row["id_fac"];
$facture["id_client"] = $row["id_client"];
$facture["id_agent"] = $row["id_agent"];
$facture["montant"] = $row["montant"];
$facture["type_paiement"] = $row["type_paiement"];
$facture["id_prod"] = $row["id_prod"];
$facture["date_vente"] = $row["date_vente"];
// push single client into final response array
array_push($response["factures"], $facture);
}
foreach ($response["factures"] as $ligne){
var_dump($ligne);
fputcsv($output,$ligne) or die ('erreur');
echo $cpt."inserted";
$cpt++;
}
fclose($file);
} else {
echo "file not found";
}
}
?>
您無法寫入http位置,請嘗試將其更改為本地目錄。
fopen('\\XXXX\\toERP\\factures.csv','w')
或只是更改保存位置
$output = fopen('\\XXXX\\toERP\\factures.csv','w'); fputcsv($output, explode(';',$ligne));
這是fputcsv的定義: http ://php.net/manual/en/function.fputcsv.php
作為第二個參數,您需要提供一個包含字段的數組。
$ ligne在您的情況下,是一個具有一個元素的數組:['factures']這是另一個數組,因此您需要更改foreach以匹配以下形式:
foreach ($response['factures'] as $ligne)
另外,正如其他人提到的那樣:您需要為文件名選擇本地資源,並確保您有權在其上寫。
由於您編寫的網址示例,您正在嘗試從遠程服務器打開文件。 如果看到echo插入的行,則這是最可能出現的問題。
這段代碼對我有用:
<?
$server="mysql12.000webhost.com";
$user="a2258793_star";
$password="star123";
$db="a2258793_stores";
$con = mysql_connect($server,$user,$password) or die('erreur au serveur');
mysql_select_db($db) or die('erreur db');
mysql_select_db($db);
$file='toERP/factures.csv';
$fp = fopen($file,"w");
$sql = mysql_query("select * from facture") or die (mysql_error);
mysql_data_seek($sql,0);
while ($row = mysql_fetch_assoc($sql)){
$sep = "";
$comma = "";
foreach ($row as $name => $value)
{
$sep.=$comma.''.str_replace('','""',$value);
$comma =";";
}
$sep.="\n";
fputs($fp,$sep);
}
fclose($fp);
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.