我有一个像这样的数组
$rowArray = array(
array(
"http://www.website.com/article.html",
"09/18/2013",
"An article about stuff"
),
array(
"http://www.google.com",
"09/18/2013",
"The Google",
)
);
我想制作一个像这样的.txt文件:
http://www.website.com/article.html,09/18/2013,"An article about stuff"\r\n
http://www.google.com,09/18/2013,"The Google"\r\n
注意带有空格和逗号的字符串周围的“引号”以及\ r \ n返回。
我试过这个:(我把标题设置在哪里和他们的好)
$op = fopen("php://output", "w");
foreach($rowArray AS $row) {
$row[] = "\r\n";
fputcsv($op, $row);
}
fclose($op);
这个
$row[] = "\r\n";
fwrite($op, implode(",",$row));
这个
echo mb_convert_encoding(implode(",", $row) . "\r\n", 'UTF-8');
我需要转换它,因为我在数据库中从网页上删除了字符,文本编辑器需要使用UTF-8。谁能帮我?我似乎无法获得双引号和\ r \ n和“引号”。提前谢谢。
答案 0 :(得分:0)
尝试
foreach ($rowArray as $row){
$row[2] = '"' . $row[2] . '"';
fwrite($op, implode(',', $row) . "\r\n");
}
答案 1 :(得分:0)
好的,这就是我需要的东西
我最终做的是重写fputcsv函数。我只改变了三行,然后在下面留下了评论,这样你就可以看到我改变了什么。
protected function _putcsv(&$handle, $fields = array(), $delimiter = ',', $enclosure = '"') {
$str = '';
$escape_char = '\\';
// I changed $value to $valueRaw so I could convert it easily
foreach ($fields as $valueRaw) {
// I added this line to convert to UTF-8 to set the $value variable
$value = mb_convert_encoding($valueRaw, 'UTF-8');
if (strpos($value, $delimiter) !== false ||
strpos($value, $enclosure) !== false ||
strpos($value, "\n") !== false ||
strpos($value, "\r") !== false ||
strpos($value, "\t") !== false ||
strpos($value, ' ') !== false) {
$str2 = $enclosure;
$escaped = 0;
$len = strlen($value);
for ($i = 0; $i < $len; $i++) {
if ($value[$i] == $escape_char) {
$escaped = 1;
} else if (!$escaped && $value[$i] == $enclosure) {
$str2 .= $enclosure;
} else {
$escaped = 0;
}
$str2 .= $value[$i];
}
$str2 .= $enclosure;
$str .= $str2 . $delimiter;
} else {
$str .= $value . $delimiter;
}
}
$str = substr($str, 0, -1);
// I changed the string ending from just "\n" to "\r\n"
$str .= "\r\n";
return fwrite($handle, $str);
}
问题解决了。谢谢你的回答!