我有一个.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
Run Code Online (Sandbox Code Playgroud)
我想做的是解析这个广告,将值变为更易读的格式,如果可能的话,可能会变成数组.
谢谢
Mic*_*ter 58
你可以这样轻松地做到这一点
$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 />';
}
Run Code Online (Sandbox Code Playgroud)
首先使用该函数打开文本文件file_get_contents()
,然后使用该函数剪切换行符上的字符串explode()
.这样,您将获得一个包含所有行分隔的数组.然后使用该函数,array_shift()
您可以删除第一行,因为它是标题.
获取行后,您可以遍历数组并将所有信息放入一个名为的新数组中$info
.然后,您将能够从第0行开始获取每行的信息.因此,例如$info[0]['description']
会Some text goes here
.
如果你想将图像放在一个数组中,你也可以使用它explode()
.只需将它用于第一行:$first_row_images = explode(',', $info[0]['images']);
$values = explode('^', $string);
Run Code Online (Sandbox Code Playgroud)
或者,如果你想要更好的东西:
$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])
);
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,我遇到的最好和最简单的例子就是file()方法.
$array = file("myfile");
foreach($array as $line)
{
echo $line;
}
Run Code Online (Sandbox Code Playgroud)
这将显示文件中的所有行,这也适用于远程URL.
简单明了.
REF:IBM PHP Parse
我想贡献一个提供原子数据结构的文件。
$lines = file('some.txt');
$keys = explode('^', array_shift($lines));
$results = array_map(
function($x) use ($keys){
return array_combine($keys, explode('^', trim($x)));
},
$lines
);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
86922 次 |
最近记录: |