I have a text file and I want each line to be an element of an array.
$file = file("books.txt");
$split = explode("\n", $file);
Then if I try to print an element of the array:
echo "$split[0]";
I get no output.
Because file("books.txt") gives already an array resulting from exploding by newline, you can echo "$file[0]";, no need for further exploding.
Related
I am getting data from a page like this:
<?php $speaker = $page->uri();
$speakerEvents = page('program')->grandchildren()->filter(function($child) use($speaker) {
$speakers = $child->speaker()->toStructure();
return $speakers->findBy('selectspeaker', $speaker);
});
echo $speakerEvents;
?>
It's output is:
"page/page/pageIWant
page/page/pageIWant"
The Result I want is
pageIWant
pageIWant
I tried to get the last name with
echo basename($speakerEvents);
But I only get one of the last pageIWant
How do I get the last pages without removing the first URL?
Use the explode method to get array of URL
<?php
$link = $_SERVER['PHP_SELF'];
$link_array = explode('/',$link);
echo $page = end($link_array);
?>
If your output is
page/page/pageIWant
page/page/pageIWant
<?php
$text = "page/page/pageIWant";
$text_arr = explode('/',$text);
echo $page = end($text_arr);
// this will print: pageIWant
?>
Your string has a line break as path separator. You need to split lines by either \r\n (CR-LF), \n, or \r which can be done with preg_split. If you can ensure one of the formats, you can also use the simple explode function.
foreach (preg_split('~(?:\r?\n|\r)~u', $speakerEvents) as $path)
echo basename($path) , PHP_EOL;
As AbraCadaver noted, you can add the flag PREG_SPLIT_NO_EMPTY to preg_split if you do not want empty lines to be handled.
If the double qoutes you show in the question are part of the string, you need further more to trim the string:
foreach (preg_split('~(?:\r?\n|\r)~u', trim($speakerEvents, '"')) as $path)
echo basename($path) , PHP_EOL;
You can explode the string e.g.
$array = explode('/', 'page/page/pageIWant');
Then you can retrieve it using the index like so:
$array[(count($array) - 1)];
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 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>";
}
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 need to get the contents of a text file called file.txt. The contents of that file are:
word1,word 2,word 3 1,another word 1,
I have a config.php which includes:
$file = "file.txt";
$value = explode(",", $file);
And script.php file which will execute other commands based on $value which includes:
if (count(explode($value, $chat))>1) {
After that, it will execute a command if the $value was detected in $chat. So, I need the $value to be a separate word in file.txt.
How can I do this?
If you're looking for more flexibility, you might want to try using preg_split rather than explode, which splits on a regular expression. For example, to split on newlines and commas, you could use this:
$text = file_get_contents('text.txt');
$values = preg_split('/[\n,]+/', $text);
Testing it out:
$s = "word1,word 2\n word 3";
print_r(preg_split('/[\n,]+/', $s));
Output:
Array
(
[0] => word1
[1] => word 2
[2] => word 3
)
Putting that into your script:
$file = "file.txt";
$text = file_get_contents($file);
$values = preg_split('/[\n,]+/', $text);
Then $values is an array, which you can loop over in the other script:
foreach ($values as $value) {
// do whatever you want with each value
echo $value;
}
Reading file contents:
file_get_contents
Explode string:
explode
Get file as array (each line => one item):
file
BTW: a short google would already answer your question...
In config.php add this code, be sure that the file is in the same folder
$value = file_get_contents('file.txt');
Then in script.php add this code:
$pieces = explode(",", $value);
Read more about file_get_contents and explode. (Click on the names)