1

How can I change a text file with a list of words, each on their own line (without commas), into one array, with comma separating?

I guess, what do you use to manipulate PHP arrays and strings to be able to interchange the data?

explode?

The file looks like this:

This
Is
The
File
I
Want
Changed

And I want it it to look like this:

array(
    This,
    Or,
    This,
    Or,
    Even,
    This
);
1
  • 1
    Are you serious? Do some research. "php file array" Searching those MAIN keywords on google, the first thing that pops up is what you need... Don't expect other people to always lead you to the answer, honestly. Commented Sep 7, 2012 at 3:03

4 Answers 4

7

If you want it split on each line-break, use

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

Or, if you have text, not a file, that you want to explode:

$file = explode("\n", $text);

See file and explode.


But next time, please do your own research.

Sign up to request clarification or add additional context in comments.

4 Comments

+1 to both of you, But I disagree with your comment: Next time, please do your own research!. Indeed until now I did not know how easy is change a text file into an php array It is a very good question and answer...
@NomikOS Did you see Nile's comment on the question? I would say it is fairly easy to do one's own research, but I suppose some people might not think of the right search terms.
Well, Now because of you I know something new. That's is another good reason to participate in this community! 8)
most of the time when you search for something like this you get flooded with SO results. most people attempt a few searches but give up quickly and head over here. if you provide a good answer then subsequent searches for "how to change a text file into a php array" will hit this page, theyll get the answer, and wont open a question
2

Very easy... do this:

$arch = file( 'your-file.txt' );

Then:

echo '<pre>'; print_r( $arch ); echo '</pre>';

Comments

2

If you want to get the array, you could use file function.

$array = file($file_path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

Comments

1

text file to change in array:=

 $text= 'test.txt';
 $fo= fopen($text,'r');
 $fr = fread($fo,filesize($fo));

 $strarray = explode(' ', $fr);

 print_r($strarray);

Comments

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.