0

Am new to PHP and am using php5.2, I need to convert a file content into a two-dimensional array, ie my file content will be

"Higher Studies" => "#",
"Symposiums" => "#",
"Conferences" => "#"

And my expected output is,

Array ( [Higher Studies] => # [Symposiums] => # [Conferences] => # )

PHP functions I tried to achieve this,

$values = file_get_contents($url);
echo $values;
$array = explode(",", $values);

$array = array(file_get_contents($url));

$array = file('http://localhost/test1.php');

And finally I am getting an answer like this,

Array ( [0] => "Higher Studies" => "#", [1] => "Symposiums" => "#", [2] => "Conferences" => "#" )

Is this the possible way we can read from a file or Is it possible to get a solution as like What I expected??

1 Answer 1

2

you should read it via file, then go for each row, split and store in array

$array = array();
$values = file($url);
foreach ($values as $idx => $row)
{
    list($k, $v) = explode(' => ', $row);
    $k = trim($k, '"');
    $v = trim($v, '",');
    $array[$k] = $v;
}
print_r($array);

or you can do:

$values = file_get_contents($url);
eval('$array = array('.$values.');');
print_r($array);
Sign up to request clarification or add additional context in comments.

5 Comments

Is eval() a good choice or splitting the contents as you said before can be good??
eval can be prohibited on some hosting systems, so it is better to do with file/split - but if you're sure about file contents, and server - eval will be faster
Yeah it works good. May be support will be prohibitted after some days too in my hosting right. So better to go with split? How can I split things like this.
In that am getting the output for values with ",
Thanks Ilya Bursov. I have edited the answer as it works good for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.