0

I have a txt file that contains an array like this:

array (
  0 => 'jack',
  1 => 'alex'
)

I want to use this array in my PHP code but it is not working as on this example which returns a

$list=  file_get_contents(myfile.txt); 
echo $list[0];

How can I convert it ?

1
  • 2
    The array hasn't really been declared in myfile.txt. It's kinda' naked. Commented Oct 17, 2014 at 15:07

2 Answers 2

3

Rather have the array serialized or json_encoded, inside that file. Then, when reading it, just unserialize or json_decode in $list

Example:

$list = unserialize(file_get_contents(myfile.txt));
Sign up to request clarification or add additional context in comments.

4 Comments

with unserialize show this error Notice: unserialize() [function.unserialize]: Error at offset 0 of 40 bytes and with json_decode not show any thing
Make sure, the contents of myfile.txt is a serialized or json enconded array, otherwise, won't work
@user2511140, you can't just unserialize the current data in myfile.txt. You have to put a serialized array in myfile.txt. (User serialize on the array first, then put the output of that in myfile.txt)
Thanks @w0rldart. i use json_encode for write to file and use json_decode to for $list then problem solved. :)
0

To answer the quextion - eval looks like it will handle the array (Array has been output with var_export ?)

BUT exec'ing unknown code is a bad idea, W0rldart has the better ways to do it (json would be my preference)

1 Comment

Don't you mean eval instead of exec?

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.