Reputation: 5148
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 !
Upvotes: 0
Views: 176
Reputation: 1626
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.
Upvotes: 4
Reputation: 54729
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.
Upvotes: 2