我想首先说我不是PHP开发人员。这是我用PHP编写的第一个应用程序。我还要为没有多少代码显示而道歉。
我有一个CSV文件,我需要在每行中运行,并为每个记录添加一个新列,其中包含我通过函数调用生成的值。我能够弄清楚的大多数PHP是编写函数来获取额外的数据并将文件打开为CSV。
$csvFile = fopen('records.csv');
$csv = fgetcsv($csvFile);
foreach($csv as $line){
// Create a new code to populate the new column with:
$linkCode = getUniqueCode();
// Add the column to the record
// Save the record back to the csv
}
// Save the CSV back to a file
再次,抱歉缺少更多代码,但我找不到太多资源来处理我正在做的事情。
编辑:这里有更多代码,解析开始结合但尚未完成。我现在遇到的问题是CSV似乎没有被正确解析。我的CSV文件看起来像这样(没有引号):
David Long,dave@davejlong.com
James Allen,james@davejlong.com
我的代码如下所示:
<?php
//require_once "Mail.php";
//require_once "Mail/mime.php";
$facebook = '*****';
$twitter = '*****';
$band = '*****';
$album = '******';
$paypal = '******';
$download = '******';
function makeConnection(){
$host=$_ENV{'DATABASE_SERVER'};
$username="*******";
$password="*********";
$db_name="**********";
$con = mysql_connect("$host", "$username", "$password")or die(mysql_error());
mysql_select_db("$db_name")or die(mysql_error());
return $con;
}
function makeCode($email, $name){
$codeused = true;
do{
$code = substr(microtime().'_'.$GLOBAL['album'],2,6);
$escapeCode = mysql_escape_string($code);
$query = mysql_query("SELECT * FROM downloads WHERE code='$code'")or die(mysql_error());
if(!mysql_num_rows($query))$codeused = false;
else $codeused = true;
}while($codeused);
$email = mysql_escape_string($email);
$name = mysql_escape_string($name);
$download = mysql_escape_string($GLOBALS['download']);
$query = mysql_query("INSERT INTO downloads(email,name,code,download) VALUES('$email','$name','$code','$download')")or die(mysql_error());
return 'http://********'.$code;
}
$conn = makeConnection();
if(($csvFile = fopen('emails.csv','r')) !== false && ($resultCsv = fopen('result.csv','w')) !== false){
while (($data = fgetcsv($csvFile)) !== false){
$data[] = makeCode($data[1],$data[0]);
echo $data;
fputcsv($resultCsv, $data);
}
fclose($csvFile);
fclose($resultCsv);
}
?>
答案 0 :(得分:2)
这样的事情:
ini_set('auto_detect_line_endings',TRUE); // Fixes problem with Mac Excel
if (($csvFile = fopen("records.csv", "r")) !== false && ($resultCsv = fopen('result.csv', 'w')) !== false) {
while (($data = fgetcsv($csvFile)) !== false) {
$data[] = getUniqueCode();
fputcsv($resultCsv, $data);
}
fclose($csvFile);
fclose($resultCsv);
}