【问题标题】:PHP - parsing a txt filePHP - 解析一个txt文件
【发布时间】:2011-07-15 01:01:50
【问题描述】:

我有一个包含以下详细信息的 .txt 文件:

ID^NAME^DESCRIPTION^IMAGES
123^test^Some text goes here^image_1.jpg,image_2.jpg
133^hello^some other test^image_3456.jpg,image_89.jpg

我想做的是解析此广告,将值转换为更易读的格式,如果可能的话,可能转换为数组。

谢谢

【问题讨论】:

    标签: php text-parsing


    【解决方案1】:

    您可以通过这种方式轻松做到这一点

    $txt_file    = file_get_contents('path/to/file.txt');
    $rows        = explode("\n", $txt_file);
    array_shift($rows);
    
    foreach($rows as $row => $data)
    {
        //get row data
        $row_data = explode('^', $data);
    
        $info[$row]['id']           = $row_data[0];
        $info[$row]['name']         = $row_data[1];
        $info[$row]['description']  = $row_data[2];
        $info[$row]['images']       = $row_data[3];
    
        //display data
        echo 'Row ' . $row . ' ID: ' . $info[$row]['id'] . '<br />';
        echo 'Row ' . $row . ' NAME: ' . $info[$row]['name'] . '<br />';
        echo 'Row ' . $row . ' DESCRIPTION: ' . $info[$row]['description'] . '<br />';
        echo 'Row ' . $row . ' IMAGES:<br />';
    
        //display images
        $row_images = explode(',', $info[$row]['images']);
    
        foreach($row_images as $row_image)
        {
            echo ' - ' . $row_image . '<br />';
        }
    
        echo '<br />';
    }

    首先使用函数file_get_contents() 打开文本文件,然后使用函数explode() 在换行符处剪切字符串。这样,您将获得一个所有行分开的数组。然后使用函数array_shift() 可以删除第一行,因为它是标题。

    获取行后,您可以遍历数组并将所有信息放入一个名为$info 的新数组中。然后,您将能够从第 0 行开始获取每行的信息。因此,例如 $info[0]['description'] 将是 Some text goes here

    如果您也想将图像放入数组中,您也可以使用explode()。只需将其用于第一行:$first_row_images = explode(',', $info[0]['images']);

    【讨论】:

    • @Michiel Pater 感谢您的提醒,问题是,当我得到图像时, var_dump() 只输出: IMAGES 123IMAGES 123IMAGES 123IMAGES 123IMAGES 123IMAGES 123IMAGES 123 任何想法?
    • @terrid25:你试过我的新(更新)代码了吗?如果是,请发布您用于var_dump() 的代码。
    • @terrid25:我正在使用以下代码:var_export(explode(',', $info[1]['images']));。它输出:array ( 0 =&gt; 'image_1.jpg', 1 =&gt; 'image_2.jpg', ).
    • 是的,我尝试了更新的代码。 var_dump($info[1]['images']); 给我NULL。我的完整代码是$txt_file = file_get_contents('test.txt'); $rows = explode("\r\n", $txt_file); foreach($rows as $row =&gt; $data) { $row_data = explode('^', $data); $info[$row]['id'] = $row_data[0]; $info[$row]['name'] = $row_data[1]; $info[$row]['description'] = $row_data[2]; $info[$row]['images'] = $row_data[3]; var_dump($info[1]['images']); }
    • @terrid25:那你一定在做一些不同的事情。当我尝试使用相同的代码时,它会输出string(23) "image_1.jpg,image_2.jpg"。您的文本文件中的内容是否与您在问题中发布的内容相同?
    【解决方案2】:

    使用explode()fgetcsv()

    $values = explode('^', $string);
    

    或者,如果你想要更好的东西:

    $data = array();
    $firstLine = true;
    foreach(explode("\n", $string) as $line) {
        if($firstLine) { $firstLine = false; continue; } // skip first line
        $row = explode('^', $line);
        $data[] = array(
            'id' => (int)$row[0],
            'name' => $row[1],
            'description' => $row[2],
            'images' => explode(',', $row[3])
        );
    }
    

    【讨论】:

    • 我如何访问它们的值?
    • 学习 PHP。 foreach($data as $row) 然后例如$row['id']
    【解决方案3】:

    到目前为止,我遇到的最好和最简单的例子就是 file() 方法。

    $array = file("myfile");
    foreach($array as $line)
           {
               echo $line;
           }
    

    这将显示文件中的所有行,这也适用于远程 URL。

    简单明了。

    参考:IBM PHP Parse

    【讨论】:

      【解决方案4】:

      我想贡献一个提供原子数据结构的文件。

      $lines = file('some.txt');
      $keys = explode('^', array_shift($lines));
      $results = array_map(
          function($x) use ($keys){
              return array_combine($keys, explode('^', trim($x)));
          }, 
          $lines
      );
      

      【讨论】:

      • 漂亮!这也比其他方法更完整,因为它实际上使用标题行。
      【解决方案5】:

      尝试fgetcsv()^ 作为分隔符:

      $file = fopen($txt_file,"r");
      print_r(fgetcsv($file, '^'));
      fclose($file);
      

      http://www.w3schools.com/php/func_filesystem_fgetcsv.asp

      【讨论】:

        【解决方案6】:
        <?php
        $row = 1;
        if (($handle = fopen("test.txt", "r")) !== FALSE) {
            while (($data = fgetcsv($handle, 1000, "^")) !== FALSE) {
                $num = count($data);
                echo "<p> $num fields in line $row: <br /></p>\n";
                $row++;
                for ($c=0; $c < $num; $c++) {
                    echo $data[$c] . "<br />\n";
                }
            }
            fclose($handle);
        }
        ?>
        

        【讨论】:

        • 如何分割图像?
        【解决方案7】:

        好的,没有看到修改后的版本,所以这里重做。它很可能是一个使用插入符号作为分隔符的 CSV 文件,所以...

        $fh = fopen('yourfile.txt');
        $headers = fgetcsv($fh, 0, '^');
        $details = array();
        while($line = fgetcsv($fh, 0, '^')) {
           $details[] = $line;
        }
        fclose($fh);
        

        【讨论】:

          【解决方案8】:

          你用一个列表,分解字符串后拆分“image_1.jpg,image_2.jpg”:

          list($number, $status, $text, $images) = explode("^", $data);
          
          $splited_images= preg_split(',', $images);
          

          【讨论】:

            【解决方案9】:

            我的解决方案

            function parseTextFile($file){
                if( !$file = file_get_contents($file))
                    throw new Exception('No file was found!!');
                $data = [];
                $firstLine = true;
                foreach(explode("\n", $file) as $line) {
                    if($firstLine) { 
                        $keys=explode('^', $line);
                        $firstLine = false; 
                        continue; 
                    } // skip first line
                    $texts = explode('^', $line);
                    $data[] = array_combine($keys,$texts);
                }
                return $data;
            }
            

            【讨论】:

              猜你喜欢
              • 2015-10-06
              • 1970-01-01
              • 1970-01-01
              • 2016-05-21
              • 1970-01-01
              • 2011-05-12
              • 1970-01-01
              • 1970-01-01
              • 2014-03-28
              相关资源
              最近更新 更多