PHP - 解析一个txt文件

36

我有一个包含以下详细信息的 .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
我想要做的是解析这个广告并将值以更易读的格式呈现,如果可能的话,放入数组中。
谢谢。
9个回答

69

您可以轻松地通过以下方式实现

$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的新数组中。然后,您将能够从零开始逐行获取信息。例如,$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
是的,我复制粘贴了。我的输出现在是 array ( 0 => 'IMAGES 123', ) - terrid25
@Michiel Pater 好的,有所改进。但问题是,我需要每一行的所有信息,除了标题值之外。你为我写的代码只返回第一行的值。谢谢。 - terrid25
@terrid25:我又更新了我的答案。现在它将直接输出每一行的所有信息。使用函数array_shift()移除了标题。请告诉我你有什么进展。 - Michiel Pater
这并不意味着从标题行推断出标题。 - Lloyd Moore
显示剩余9条评论

9
使用 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])
    );
}

我该如何访问这些值? - terrid25
学习PHP。使用foreach($data as $row),然后例如$row['id'] - ThiefMaster

8

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

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

这将显示文件中的所有行,也适用于远程URL。
简单明了。
参考: IBM PHP解析

5

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

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

1
太好了!这种方法比其他方法更完整,因为它实际上使用了标题行。 - demonkoryu

3

0

我的解决方案

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

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

我该如何拆分这些图像? - terrid25

0

好的,没有看到编辑过的版本,所以重新来一遍。很可能是一个使用插入符作为分隔符的 CSV 文件,所以...

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

0
使用列表,将字符串“image_1.jpg,image_2.jpg”分割成多个元素:
list($number, $status, $text, $images) = explode("^", $data);

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接