问题描述
我有一个.txt文件,其中包含以下详细信息:
I have a .txt file that has the following details:
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.
谢谢
推荐答案
您可以通过这种方式轻松实现
$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()
可以删除第一行,因为它是标题.
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.
获取行之后,可以遍历数组并将所有信息放入名为$info
的新数组中.然后,您将能够从零行开始获取每行的信息.因此,例如$info[0]['description']
将是Some text goes here
.
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
.
如果您也想将图像放入数组中,也可以使用explode()
.只需在第一行中使用它即可:$first_row_images = explode(',', $info[0]['images']);
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']);
这篇关于PHP-解析txt文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!