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);
Related
I have a big text file, split by new lines and on every line elements split by ';', like this:
1;1;20;3.6;0%;70%;25%;0%;5%;
1;2;80;4;45%;20%;20%;15%;0%;
1;3;80;4;40%;35%;5%;20%;0%;
1;4;20;3.6;15%;40%;38%;5%;2%;
1;5;20;3.6;30%;18%;33%;20%;0%;
1;6;80;4;27%;47%;23%;3%;0%;
What I would like to do is with PHP is to read the file correctly and access a specific element in any row, for example on row 2, element 3 (maybe, [1][2], if considered as indexes) and print it.
<?php
//split by new line
$text = fopen("public/data/data1.txt", "r");
if ($text) {
while (($lines = fgets($text)) !== false) {
//split by ;
$line = explode(';', $lines);
//access a specific element
}
fclose($text);
} else {
// error opening the file.
}
?>
Does somebody know how I could access this elements?
You can explode the string twice.
First on lines, then on ;.
$arr = explode(PHP_EOL, $str);
Foreach($arr as &$line){
$line = explode(";", $line);
}
https://3v4l.org/5fbvZ
Then echo $arr[1][2]; will work as you wanted
I have a multiline string and that have 2 words in line.
I want within a while loop while reading the script line by line
get the 1st word and 2nd word.
$multilinestring="name1 5
name2 8
name3 34
name5 55 ";
The result i want to have while i am reading the the string line by line is to get
2 more strings
$firstword and $secondword
Thank you all in advance!
Use this:
$eachLine = explode(PHP_EOL, $multilinestring); // best practice is to explode using EOL (End Of Line).
foreach ($eachLine as $line) {
$line = explode(" ", $line);
$firstword = $line[0];
$secondword = $line[1];
}
What's the point in using a while loop to do this? Use foreach loop to achieve this:
foreach (explode("\n", $multilinestring) as $line) {
$line = explode(" ", $line);
print_r($line);
}
If this is really a text file you want to read, then you'd be better of to use fgets() or read the file to an array completely with file() and use explode() afterwards. Consider this code:
$arr = file("somefile.txt"); // read the file to an array
for ($i=0;$i<count($arr);$i++) { // loop over it
$tmp = explode(" ", $arr[$i]); // splits the string, returns an array
$firstword = $tmp[0];
$secondword = $tmp[1];
}
I found interesting problem while I was trying to achieve something simple like splitting string into array. The only difference here is that Im trying to take the string from .txt file
My code is the following:
$handle = fopen("input.txt", "r"); // open txt file
$iter = fgets($handle);
// here on first line I have the number of the strings which I will take. This will be the for loop limitation
for ($m = 0; $m < $iter; $m++)
{
$string = fgets($handle); // now getting the string
$splited = str_split($string); //turn it into array, this is where problem appears
print_r ($splited); // just show the array elements
echo "<br>";
echo count($splited);
echo "<br>";
}
This is the content of my .txt file
4
abc
abcba
abcd
cba
I tried with array_filter() and all other possible solutions/functions. Array filter and array diff are not removing the empty elements, no idea why... Also in my txt file there are no blank spaces or anything like that. Is this a bug in a str_split function ? Any logic behind this ?
The extra whitespace is a newline. Each row except the last technically contains all of the text contents you see, plus a newline.
You can easily get rid of it by e.g.
$string = rtrim(fgets($handle));
Also, fgets($fp); makes no sense since there's no variable $fp, should be fgets($handle); given your above code.
Trimming the spaces and need to change your fgets($fp) to fgets($handle) as there's no variable like of $fp.You need to update your code into as
for ($m=0;$m<$iter;$m++)
{
$string = trim(fgets($handle)); //
$splited = str_split($string); //turn it into array, this is where problem appears
print_r ($splited); // just show the array elements
echo "<br>";
echo count($splited);
echo "<br>";
}
$file = fopen("procinfo.txt", "r") or exit("Unable to open file!");
$proc =array();
$param=array();
while (!feof($file))
{
$arr = fgets($file);
$all=explode(",", "$arr");
preg_match('/^#./', $all[0], $matches);// matches lines in an array that has a #
$proc[] = $matches[0];
preg_match('/^P./', $all[0], $matches);// matches lines in an array that has a P at the beggining
$param [] = $matches[0];
}
fclose($file);
I want to be able to get all the matches into separate arrays to retrieve them easier
If your code is giving you a warning "PHP Notice: Undefined offset: 0 in ..." it is because there are times where $matches is array() (empty array) and the index 0 does not exist.
I believe the only thing you might need to do is change
$proc[] = $matches[0];
to
if (count($matches)) $proc[] = $matches[0];
and similarly change
$param[] = $matches[0];
to
if (count($matches)) $param[] = $matches[0];
Not only will these changes get rid of you offset warnings, but they will also prevent populating $proc and $param with empty elements when the line is not a match.
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
?>