开发者

problem in reading txt file in php

im looking for a way to read a file into an array and get what i want .

this is the code i used to read a file into an array

$Path = 'dewp/pix/info.txt';
$productsArray = file($dirPath, FILE_IGNORE_NEW_LINES);
foreach ($productsArray as $key => &$product) {
    $arr = explode("\t", $product);
    $product =array('album=' => $arr[0], 'singer=' => $arr[1], 'info=' => $arr[2]);
}
echo "$product['album']";

and my txt file contains :开发者_开发问答

album= Prisoner
singer= Jackobson
info= Love song about GOD , so so so so .

but nothing happened and i couldnt get album - singer or info string !

i need to explode special strings like album= to find out the values !


That data looks like .ini files, why don't you try using parse_ini_file(), like

<?php
$Path = 'dewp/pix/info.txt';
$product = parse_ini_file($path);
echo $product['album'];

If you have multiple products, you could have the files like

[some_product]
artist=Foo
singer=Bar
info=Lorem ipsum bla bla

[other_product]
artist=Foobar
singer=The Dude
info=Dolor sit amet bla bla bla

and do

<?php
$Path = 'dewp/pix/info.txt';
$products = parse_ini_file($path, true);
echo $products['some_product']['album'];

Also, in your code, you set a variable $Path, and then use $dirPath on the next line. And it overwrites the $product variable for each line in the loop.


That's because each line in your file is an element in the array, the file() function does not create any keys, you have to split each element by the '= ' string to get an array of two elements (a key and a variable).

$path = 'dewp/pix/info.txt';
$lines = file($path, FILE_IGNORE_NEW_LINES);
$product = array();
foreach ($lines as $line) {
    $arr = explode("= ", $line);
    $product[$arr[0]] = $arr[1];
}
echo "{$product['album']}";

Note: The FILE_IGNORE_NEW_LINES flag just removes the '\n' at the end of each array element.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜