1

Try to get arrays from a file like...

data.txt

Array
(
    [0] => 288
    [1] => 287
    [2] => 173
)

my.php

$data = file('data.txt');

foreach ($data as $id) {
    echo $id." - ";
}

Why its echo all arrays back ? like data.txt

Why not echo like 288 - 287 - 173 ?

CLOSED : I using JSON now

5
  • Does your data.txt file actually contain the result of print_r? Commented Nov 29, 2012 at 12:47
  • yes :( how can i do it ? Commented Nov 29, 2012 at 12:48
  • 2
    @l2aelba you can write data into serialize format.When you read data then unserialize Commented Nov 29, 2012 at 12:49
  • How are you dumping data to data.txt file ? And why is it in this format ? Any specific reason ? Commented Nov 29, 2012 at 12:53
  • fail foreach function ? or what ? Commented Nov 29, 2012 at 12:58

2 Answers 2

3

When saving your data, get the string representation using serialize:

$str = serialize($arr);

You can then use unserialize to decode your array:

$arr = unserialize(file(data.txt));
Sign up to request clarification or add additional context in comments.

8 Comments

+1, BTW, I'd use json_encode/json_decode because saved data will be flexible enough to be used with other languages.
@PLB I thought about that, but while json_encode is good enough for numeric, string literals, it fails for more complex data types.
what do you mean in failure?
@l2aelba It will work in most cases but Asad is right at some point some data may be lost. However with simple data, I'd advise you to go with json.
@l2aelba Whatever floats your boat :) Just remember, you are restricted to string and numeric data types in your array.
|
2

Your method loads the data in data.txt as a string, and php will not parse it as code. Try

$data = eval(file(data.txt));

See more on eval here: PHP manual on eval

Also note that the syntax in data.txt is invalid. You want:

array(288, 287, 173);

PHP will automatically create the indexes as needed.

On a second note, this is probably not the best way to go about it. Not knowing what you aim to achieve here, but would it not be better to just have the array set in your php file?

2 Comments

eval on a txt file ... really ?
if my syntax look like i posted ?

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.