Solved

How do I turn a txt file with multiple lines into a php array with the explode function?

Posted on 2012-03-30
7
252 Views
Last Modified: 2012-03-31
I have a form on my website that adds user inputs to a file called data.txt. Here is the php code that the form triggers:

<?php
$myFile = "data.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$firstName = $_POST["firstName"]." ";
fwrite($fh, $firstName);
$lastName = $_POST["lastName"]." ";
fwrite($fh, $lastName);
$email = $_POST["email"]." \n";
fwrite($fh, $email);
fclose($fh);?>

Open in new window


The resulting data.txt file has multiple lines like this:

John Smith jsmith@email.com
Sam Johnson sjohnson@email.com
Steve Jones sjones@email.com

I want to use some php to turn every word, separated by spaces, into an array element in $wordArray like this:

$fh = fopen("data.txt", 'r') or die("can't open file");
$wordArray = explode(" ",fgets($fh));

But the " \n" at the end of the $email variable makes it impossible for me to access the strings on the following line correctly. For example, $wordArray[3] should be "Sam" but it's not. Any idea what I'm doing wrong?
0
Comment
Question by:shampouya
  • 2
  • 2
  • 2
  • +1
7 Comments
 
LVL 3

Expert Comment

by:animecyc
ID: 37789241
http://www.php.net/manual/en/function.file.php

Using the file method you can read a file into an array line by line. From there you can separate each line similar to how your doing it. For instance:

PHP >= 5.3
array_map(function($v) { return explode(' ', $v); }, file('data.txt'));

Open in new window


PHP < 5.3
array_map(create_function('$val', 'return explode(" ", $val);'), file('data.txt'));

Open in new window


Hopefully this helps!
0
 
LVL 10

Expert Comment

by:acbxyz
ID: 37789348
The script above would create a multidimensional array. Even if this is what most want, you asked for something different.

This should do what you asked for:
$return = explode(' ', implode(' ', array_map('trim', file('data.txt'))));

Open in new window


Another advice, space is not the best separator, because it can appear in names. Something like comma or semicolon would be better. Additional, the file creating function should filter out this letter - i.e. fwrite($fh, str_replace(';', '', $_POST['firstname']) . ';');
0
 
LVL 3

Expert Comment

by:animecyc
ID: 37789389
I agree with the above comment (It looks like I overlooked the way in which he wanted to access his data), although I don't agree with the latter part of your answer. It would make more sense to account for more than just the space character. Also, we should remove the need for a delimiter to prevent issues with the heuristic. For instance the below code would be the most reliable in my opinion in this given instance.

file_put_contents('data.txt', json_encode($_POST));

Open in new window


Then for reading the data:

$data = json_decode(file_get_contents('data.txt'));

Open in new window


Although not essentially part of the answer, just thought I would throw this out there.

Happy Coding.
0
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 
LVL 9

Expert Comment

by:rinfo
ID: 37790716
Firstly instead of writting to the file one by one build a string and add that to file as a line.
Explicitly put space before and after each of the element excluding first one  and last one .
Some thing like this.
$line = $_POST["firstName"]." ".$_POST["lastName"]." ".$_POST["email"]." \n";
and then add this line to the file
fwrite($fh, $line);

Besides its always better to use a visible delimiter like  ',' to avoid problem like your.
0
 

Author Comment

by:shampouya
ID: 37791243
acbxyz, your solution is the most understandable to me. So, can you double check that my understanding on what's going on below is correct? First, the file() function is opening the data.txt file and putting each line into an array. Then the array_map() function is applying the trim function to each element of the array we just made using file(). Then, every line is imploded, or fused together, and separated by spaces to make one long line. Then, the long line we just made is exploded into 9 different elements separated by spaces. Is my understanding correct?

$return = explode(' ', implode(' ', array_map('trim', file('data.txt'))));

btw, I will take your advice and change the spaces to semicolons.
0
 
LVL 10

Accepted Solution

by:
acbxyz earned 500 total points
ID: 37791528
You got it right. The >>array_map('trim', ...<< is to remove the new line at the end of each element.
0
 

Author Closing Comment

by:shampouya
ID: 37791778
Thanks a lot, very easy to understand explanation.
0

Featured Post

Optimizing Cloud Backup for Low Bandwidth

With cloud storage prices going down a growing number of SMBs start to use it for backup storage. Unfortunately, business data volume rarely fits the average Internet speed. This article provides an overview of main Internet speed challenges and reveals backup best practices.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
ebay api to see some data about my customers 2 30
comma true 6 33
Eloquent ORM manual paginator defaults to simple 2 23
PHP not parsing ' character 12 40
Not sure what the best email signature size is? Are you worried about email signature image size? Follow this best practice guide.
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
The viewer will the learn the benefit of plain text editors and code an HTML5 based template for use in further tutorials.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

773 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question