I am needing to turn a textfile into an array...I am not sure how to go about this because the other features ive seen for php take an entire file and put it into an array but not quite how I want it to be so I am looking for advice here..
The following is written in a textfile:
"jim kroi,richard wuu,yan kebler,justin persaud"
How can I use php to make an array where automatically a loop puts each name as an item of the array until all the names run out?
so the end result of what I am trying to do is:
$array= array("jim kroi","richard wuu","Yan kebler","justin persaud");
So a loop of some sort would basically search upto each comma and extract the name before it until all of the names run out....
There are some php substr and such functions but I cant quite think of how to do this..
Yes, I do have code, here it is:
<?php
error_reporting(-1);
$fp = fopen('numbers.csv', 'w');
fputcsv($fp, $_POST['names']);
fputcsv($fp, $_POST['numbers']);
fclose($fp);
?>
i put them all in a csv but now how can I make 2 arrays, one with name the other with numbers? http://imageshack.us/photo/my-images/215/csv.png/
using implode I get the error:
Warning: implode() [function.implode]: Bad arguments. in C:\Program Files\xampp\htdocs\xampp\something.php on line 14
<?php
error_reporting(-1);
$myFile = "testFile.txt";
$fh = fopen($myFile, 'r'); // open file
$theData = fread($fh, 5); // read file and store in var
$array = explode("\n", $theData); // explode string by lines using \n
echo implode("<br/>", $theData); // put the array back together and show each item as a line
fclose($fh);
?>
Try to use fgetcsv with a custom separator.
Something like:
$names = array_map('trim', explode(',', file_get_contents('%yourFileHere')));
Use the explode() function.
$string = "jim kroi,richard wuu,yan kebler,justin persaud";
$arrNames = explode(',', $string);
var_dump($arrNames);
see explode, read the file with file_get_contents
You can try explode;
$names = explode(',', $line);
http://php.net/manual/en/function.explode.php
it's simple
<?PHP
$myFile = "testFile.txt"; // file path and name
$fh = fopen($myFile, 'r'); // open file
$theData = fread($fh, 5); // read file and store in var
$array = explode("\n", $theData); // explode string by lines using \n
echo implode("<br/>", $theData); // put the array back together and show each item as a line
?>
Related
For storing values in a .txt file I use this code:
file_put_contents('data/vote_result.txt', implode(',', $results));
and for reading i use this:
$results = explode(',', file_get_contents('data/vote_result.txt'));
The content of vote_result.txt looks like this: 0,1,2,3
How can I store a second line in the same .txt file so that the content looks like this:
0,1,2,3
0,1,2,3
and how can I read that second line?
Read second line:
$myFile = "data/vote_result.txt";
$linesArray = file($myFile);
echo $linesArray[1]; //line 2
If you want to append a line to file, use FILE_APPEND flag in file_put_contents and concatenate "\n" with implode.
file_put_contents('data/vote_result.txt', implode(',', $results)."\n", FILE_APPEND);
Besides that you should use a database like MySQL for this, you can use the file function. Example:
$data = file('file.txt');
print $data[1]; // printing out the second line
This given you can simply add new lines just by adding a new entry in the array and then implode it with the newline character and save it via the file_put_contents function.
$content = implode("\n", $data);
file_put_contents('file.txt', $content);
I'm new in PHP. I'm trying to design a simple Glossary for Primary English Students.
I want to use a .txt as database, exploded by ":". I've got a txt like this:
Hola:Hello
Good Bye: Adios
Car:Coche
Banana:Plátano
Plane:Avión
By the moment I know how to print the whole text or one column, but can't print a single word:
<?php
$file = fopen("bank.txt", "r");
while(!feof($file)) {
echo fgets($file). "<br />";
}
fclose($file);
?>
How can I print only ONE SPECIFIC WORD?
e.g. What code is recquired to print only the second word of the third line?
Like mentioned in the comments... in the future you should inform yourself how to ask questions on SO.
Regarding your question, you should take a look at the explode-function and foreach-loops of PHP.
Example:
$data = 'Hola:Hello
Good Bye: Adios
Car:Coche
Banana:Plátano
Plane:Avión';
$arrData = array();
$lines = explode( "\n", $data );
foreach ($lines as $line) {
$words = explode( ":", $line );
$arrData[] = array( $words[0], $words[1] );
}
echo( $arrData[2][1] );
// Prints: "Coche"
This should work for you:
Just get your file into an array with file(). Then go through each line with array_map() and explode() the line by a : colon.
<?php
$lines = file("test.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$lines = array_map(function($v){
return explode(":", $v);
}, $lines);
print_r($lines); //echo $lines[0][1] <- Will print the first line, second word
?>
Or what you could also do, is change your file into a .ini file format, e.g.
Hola="Hello"
Good Bye="Adios"
Car="Coche"
Banana="Plátano"
Plane="Avión"
And then you can simply use parse_ini_file(), e.g.
<?php
$file = parse_ini_file("test.ini");
//^^^^ See also here the extension
print_r($file);
?>
I am able to read from a file and create an array however I get the following error: Notice: Undefined offset: 1. Within my array there is one element that is empty and I don't understand why it is empty.
My text file is in the following format:
#EXTINF:0,ABC family USA[]http://localhost/IpInfo/index.html
#EXTINF:0,CBC[]http://localhost/IpInfo/index1.html
#EXTINF:0,A&E[]http://localhost/IpInfo/index2.html
Here is my code:
$fh = fopen('file1.txt', 'r');
$theData = fread($fh, filesize('file1.txt'));
$arr = array();
$my_array = explode("\r\n", $theData);
foreach($my_array as $line){
$tmp = explode("[]", $line);
$arr[$tmp[0]] = $tmp[1];
}
fclose($fh);
echo '<pre>';
echo print_r($arr);
I'm not quite sure what the problem is? Any help would be much appreciated!
Thanks!
Probably your input data doesn't use \r\n as the line delimiter? I'm not sure whether I got the problem completely. Also you might want to take empty lines into account.
I would use the file() function, which simplifies to iterate over the lines of a file and can handle Windows and Unix line feeds and check for empty lines:
$arr = array();
foreach(file('a.txt') as $line){
// I'm using `trim()` here since $line
// will still contain the newline delimiter
$line = trim($line);
// Skip empty lines
if(empty($line) {
continue;
}
$tmp = explode("[]", $line);
$arr[$tmp[0]] = trim($tmp[1]);
}
echo '<pre>';
print_r($arr);
Output:
<pre>Array
(
[#EXTINF:0,ABC family USA] => http://localhost/IpInfo/index.html
[#EXTINF:0,CBC] => http://localhost/IpInfo/index1.html
[#EXTINF:0,A&E] => http://localhost/IpInfo/index2.html
)
The reason is that the explode function splits your read-in data at the "\r\n". And you have a new line after the last line, and that's what results in the last "array" with no keys or values. To fix this, replace this line : $my_array = explode("\r\n", $theData); with these:
$my_array = explode("\r\n", $theData);
array_pop($my_array);
I have a text file that has information like this
##john##eva##shawn##roger##henry##david
I want to get the very last name at the end and ingnore rest.
How'd I do that
THanks
Big file solution:
$handle = fopen("myfile.txt", "r");
$file_size = filesize("myfile.txt");
$seek_position = -1024;
fseek($handle, $seek_position, SEEK_END);
while(strpos($data = fread($handle, abs($seek_position)), '##') === false){
$seek_position = $seek_position - 1024;
if(abs($seek_position) > $file_size)
break;
fseek($handle, $seek_position, SEEK_END);
}
$val = substr(2, $data);
Small file solution:
$file_contents = get_file_contents($file_location);
$array = explode('##', $file_contents);
$val = $array[end(array_keys($array))];
unset($array);
Use fseek to quickly jump to the end of the file.
$handle = fopen("myfile.txt", "r");
fseek($handle, -20, SEEK_END);
$bytes = fread($handle, 20);
Will read the last 20 bytes of the file (and skip the rest).
Unless you know how long the last name is going to be or at least the max length of names you can't really skip just to end of a file and pull out the name.
What you need to do is read the file into a buffer and parse it either using something like explode() and '##' and getting the last element of the returned array or using strpos() to find the last occureance of '##'and reading on from there.
Here is an example with explode.
$sFileName = "file.txt";
$sContents = file_get_contents($sFileName);
$aNames = explode("##", $sContents);
$sLastName = $aNames[count($aNames)-1];
After loading the file into a variable, you can find the last ocurrence of "##" using strpos() and then read from there on using substr().
You can explode the whole string to an array and then use the php's end() function, like this:
// define our string
$string = "##john##eva##shawn##roger##henry##david";
// use the explode function to create an array using the delimiter ##
$array = explode("##", "##john##eva##shawn##roger##henry##david");
// print last object of the array using the php's end function
print end($array);
I have text file that looks like this:
1 1 1 1
1 2 3 5
4 4 5 5
I want to read this text file into array of lines and display it. Can anyone help me do this?
This should get you going: php function file
<?php
$cont = file_get_contents("data.txt");
$lines = explode("\n",$cont); // $lines is now an array containing each line
// do something with data here
?>
make sure you use the correct line endings however as Windows uses \r\n and UNIX uses \n.
you can use fopen(), fgets(). see here
eg
$f=fopen("file","r");
if($f){
while (!feof($f)) {
$line = fgets($f, 4096);
print $line;
}
fclose($f);
}
You'd want to do something like this:
<?
$filename = "somefile.txt";
$arr = file($filename);
foreach($arr as $line){
print $line . "<br />";
}
?>
This one is working for me.
$array = explode("\n", file_get_contents('file.txt'));