PHP - 解析一个txt文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5299471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 20:54:44  来源:igfitidea点击:

PHP - parsing a txt file

phptext-parsing

提问by terrid25

I have a .txt file that has the following details:

我有一个 .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

What I'd like to do, is parse this ad get the values into a more readable format, possibly into an array if possible.

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

Thanks

谢谢

回答by Michiel Pater

You can do that easily this way

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

$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 />';
}

First you open the text file using the function file_get_contents()and then you cut the string on the newline characters using the function explode(). This way you will obtain an array with all rows seperated. Then with the function array_shift()you can remove the first row, as it is the header.

首先使用函数打开文本文件file_get_contents(),然后使用函数剪切换行符上的字符串explode()。通过这种方式,您将获得一个所有行都分开的数组。然后使用该功能,array_shift()您可以删除第一行,因为它是标题。

After obtaining the rows, you can loop through the array and put all information in a new array called $info. You will then be able to obtain information per row, starting at row zero. So for example $info[0]['description']would be Some text goes here.

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

If you want to put the images in an array too, you could use explode()too. Just use this for the first row: $first_row_images = explode(',', $info[0]['images']);

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

回答by ThiefMaster

Use explode()or fgetcsv():

使用explode()fgetcsv()

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

Or, if you want something nicer:

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

$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])
    );
}

回答by Pogrindis

By far the best and simplest example of this I have come accross is quite simply the file() method.

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

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

This will display all the lines in the file, this is also applicable for a remote URL.

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

Simple and clear.

简单明了。

REF : IBM PHP Parse

参考资料:IBM PHP 解析

回答by Lloyd Moore

I would like to contribute a file that provides atomic data structures.

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

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

回答by adarshr

Try fgetcsv()with ^as the separator character:

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

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

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

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

回答by jwillmer

youse a list, and split the "image_1.jpg,image_2.jpg" after you explode the string:

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

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

$splited_images= preg_split(',', $images);

回答by Marcos

My solution

我的解决方案

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;
}

回答by tawfekov

<?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);
}
?>

回答by Marc B

Ok, didn't see the edited version, so here's a redo. It's most likely a CSV file that uses carets as the separator, so...

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

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