从PHP中的文本文件中提取数据

时间:2014-05-21 09:03:16

标签: php

我是PHP新手,我正在尝试创建一个基本表单。此表单有一个下拉列表,用于显示产品。我想要它做的是显示价格,以及该产品所在的城市。

我有一个充当数据源的文本文件,并以这种方式格式化:

product | price | city

代码:

<?php

   $file = 'Product1.txt';
   $handle = @fopen($file, 'r');
   if ($handle) {
       while (!feof($handle)) {
           $line = fgets($handle, 4096);
           $item = explode('|', $line);
           echo '<option value="' . $item[0] . '">' . $item[0]. ' '.$item[1]. ' '.$item[2].'</option>' . "\n";
       }
       fclose($handle);      
   }
   ?>

   

总的来说,当我填充下拉列表时,它运行正常,我已经扩展了页面,希望获得更多。但是,当我尝试在页面末尾回显$item[1]$item[2]时,我什么都没得到。

有人能告诉我我错过了什么吗?我试过在这个问题上寻找教程,但无济于事。谢谢。

<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $_POST['D1'];
echo "<br>";
echo $quantity;
?>

2 个答案:

答案 0 :(得分:1)

你没有得到任何东西,因为$ item不在范围内

把$ itemData = array();在$ handle之后的顶部

   $file = 'Product1.txt';
   $handle = @fopen($file, 'r');
   $itemData = array();
   if ($handle) {
       while (!feof($handle)) {
           $itemData[] = explode('|', $line);
           $line = fgets($handle, 4096);
           $item = explode('|', $line);
           echo '<option value="' . $item[0] . '">' . $item[0]. ' '.$item[1]. ' '.$item[2].'</option>' . "\n";
       }
       fclose($handle);      
   }

它应该工作

答案 1 :(得分:0)

$data = explode(" | ", file_get_contents("data.txt"));
相关问题