tags:

views:

55

answers:

2

hey guys

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 !

+2  A: 

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.

animuson
nop . i used you code but no result ! are you sure about the code you wrote ?!
Mac Taylor
+3  A: 

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.

Zash
Simple and effective
Gordon
it works on localhost but not in website online mode , it cant only fetch the name $product['album'] and just the $product['info'] works
Mac Taylor
Are you saying that it half-works on the production server? If so, check that the file it uses is the same, has correct permissions, proper character set and line-endings.
Zash