将存储在变量中的内容写入csv文件
Writing content stored in variable to csv file
我在$StripContent
中存储了一行数据,当我回显$Stripcontent
时它显示
, , ,1 ,1415 ,Fietsen ,Omafietsen ,Avalon ,F 101 Oma Export 57cm Zwart , ,57 ,single speed remnaaf ,2017 ,21 ,249.00 ,135.00 ,19.50 ,8
然而,当我将 $Stripcontent
写入 CSV 文件时,它只写入第一个字符而不是整行。
$Get_Content = file_get_contents($newname);
$StripContent = preg_replace("/<([a-z][a-z0-9]*)[^>]*?(\/?)>/i",',', $Get_Content);
$file = $newname;
$content = file($file);
foreach($content as $lineNumber => &$lineContent) {
if($lineNumber == 0) {
$lineContent .= $StripContent . PHP_EOL;
}
}
$allContent = implode("", $content);
file_put_contents($file, $allContent);
您可以直接使用 $Stripcontent
变量直接执行此操作,而无需 foreach
部分,例如:
$Get_Content = file_get_contents($newname);
$StripContent = preg_replace("/<([a-z][a-z0-9]*)[^>]*?(\/?)>/i",',', $Get_Content);
$file = $newname;
$content = file($file);
file_put_contents($file, $Stripcontent);
如果您想存储 stripContent
字符串,此方法有效。我建议您将它包装在 try{...}catch()
之间并检查文件夹权限以避免出现问题!
或者如果您想使用 CSV 的内置函数,您可以使用 fputcsv
(offical documentation):
<?php
$list = array (
array('aaa', 'bbb', 'ccc', 'dddd'),
array('123', '456', '789'),
array('"aaa"', '"bbb"')
);
$fp = fopen('file.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
?>
希望对您有所帮助!
我在$StripContent
中存储了一行数据,当我回显$Stripcontent
时它显示
, , ,1 ,1415 ,Fietsen ,Omafietsen ,Avalon ,F 101 Oma Export 57cm Zwart , ,57 ,single speed remnaaf ,2017 ,21 ,249.00 ,135.00 ,19.50 ,8
然而,当我将 $Stripcontent
写入 CSV 文件时,它只写入第一个字符而不是整行。
$Get_Content = file_get_contents($newname);
$StripContent = preg_replace("/<([a-z][a-z0-9]*)[^>]*?(\/?)>/i",',', $Get_Content);
$file = $newname;
$content = file($file);
foreach($content as $lineNumber => &$lineContent) {
if($lineNumber == 0) {
$lineContent .= $StripContent . PHP_EOL;
}
}
$allContent = implode("", $content);
file_put_contents($file, $allContent);
您可以直接使用 $Stripcontent
变量直接执行此操作,而无需 foreach
部分,例如:
$Get_Content = file_get_contents($newname);
$StripContent = preg_replace("/<([a-z][a-z0-9]*)[^>]*?(\/?)>/i",',', $Get_Content);
$file = $newname;
$content = file($file);
file_put_contents($file, $Stripcontent);
如果您想存储 stripContent
字符串,此方法有效。我建议您将它包装在 try{...}catch()
之间并检查文件夹权限以避免出现问题!
或者如果您想使用 CSV 的内置函数,您可以使用 fputcsv
(offical documentation):
<?php
$list = array (
array('aaa', 'bbb', 'ccc', 'dddd'),
array('123', '456', '789'),
array('"aaa"', '"bbb"')
);
$fp = fopen('file.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
?>
希望对您有所帮助!