我正在尝试编写用于解析上传的.csv
文件的代码。我写了以下代码。控制器以数组的形式生成CSV文件的行,我也尝试使用print_r($buffer);
语句进行打印,并获得预期的输出。虽然可以使用echo $string;
打印字符串,但在保存到数据库之前,我无法将它们传递到文本字段进行编辑。
SiteController
public function actionImport()
{
$buffer[] = array();
if(isset($_POST['submitCSV'])){
$filename=$_FILES['filename']['tmp_name'];
$fp = fopen("$filename","r");
if($fp){
$i = 0;
while(($buffer[$i++] = fgetcsv($fp,1000,",")) !== false)
{}
if(!feof($fp))
echo "Echo: Unexpected fgets() fail\n";
}
fclose($fp);
unset($_POST['submitCSV']);
}
$this->render('index',array('buffer'=>$buffer));
}
查看(的index.php)
<div class="form">
<?php echo CHtml::beginForm('site/import',$method='post',$htmlOptions =array('enctype'=>'multipart/form-data')); ?>
<div class="row">
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<input type="file" name="filename" value="file">
<?php
echo CHtml::submitButton('Submit', array('name'=>'submitCSV'));
foreach($buffer as $line)
foreach($line as $string)
echo CHtml::activeTextField($string,$htmlOptions = array('value'=>$string));
?>
</div>
<?php echo CHtml::endForm(); ?>
答案 0 :(得分:0)
在你的控制器中,尝试类似:
public function actionImport()
{
if (isset($_POST['submitCSV'])) {
$filename = $_FILES['filename']['tmp_name'];
$fp = fopen("$filename", "r");
if($fp) {
while(($buffer = fgetcsv($fp,1000,",")) !== false)
{
}
if(!feof($fp)) {
echo "Echo: Unexpected fgets() fail\n";
}
}
fclose($fp);
if (count($buffer)) {
$this->render('index',array('buffer' => $buffer));
}
}
}
在你看来:
<? foreach ($buffer as $line): ?>
<p><? CHtml::activeTextField($line, array('class' => 'login_textbox', 'style' => 'width:100%', 'value' => $line)); ?> </p>
<? endforeach; ?>
您将一组数据(由CSV行组成)传递给视图,然后迭代数组并为每个数据渲染一个文本字段。确保已启用short_tags。