问题
I am trying to write the code for parsing the uploaded .csv
file. I have written the following code. The controller generates the rows of the CSV file in the form of arrays which I have also tried to print with print_r($buffer);
statement and I get the expected output. Though the strings can be printed using echo $string;
, but I am not able to pass them to the text-fields for editing before saving to the database.
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));
}
View(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(); ?>
回答1:
In your controller, try something like:
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));
}
}
}
And in your view:
<? foreach ($buffer as $line): ?>
<p><? CHtml::activeTextField($line, array('class' => 'login_textbox', 'style' => 'width:100%', 'value' => $line)); ?> </p>
<? endforeach; ?>
You're passing an array of data (composed of your CSV lines) to your view, which is then iterating over the array and rendering a text field for each one. Make sure you have short_tags enabled.
来源:https://stackoverflow.com/questions/14536221/how-to-pass-the-data-into-the-text-fields