<?php
$urls = file('urls.txt');
foreach ($urls as $url) {
print(parse_url($url));
}
?>
parse_url takes string as argument but not array element with type string. What should I do?
There's no difference between a string and an array element of type string.
Your problem is most likely that file() by default includes in each array element the newline at the end of each line in the file. See:
http://php.net/manual/en/function.file.php
You're going to need to use FILE_IGNORE_NEW_LINES to make it not do this (see link for details)
You could take a different approach when reading the file. Take this example:
$fp = fopen('urls.txt', 'r');
while(($buffer = fgets($fp, 1024)) != NULL){
//where 1024 is maximum length of each line in file
if(gettype($buffer) == 'string'){
echo "$buffer\n";
}
}
fclose($fp);
Hope this helps you.
Related
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 am trying to read a file one word at a time. So far I have been able to use fgets() to read line by line or up to a certain amount of bytes, but that is not what I am looking for. I want one word at a time. up to the next white space, \n, or EOF.
Does anyone know how to do this in php. In c++ I just use the 'cin >> var' command.
you can do this by
$filecontents = file_get_contents('words.txt');
$words = preg_split('/[\s]+/', $filecontents, -1, PREG_SPLIT_NO_EMPTY);
print_r($words);
this will give you array of words
For some replies in this topic: I say this: Do not reinvent the wheel.
In PHP use:
str_word_count ( string $string [, int $format [, string $charlist ]] )
format:
0 = Return only the number of words;
1 = Return an array;
2 = Return an associative array;
charlist:
Charlist are characters which you consider a word.
Function.str-word-count.php
[CAUTION]
Nobody know anything about the size of your file content, if your file contents is big, exists many flexible solutions.
(^‿◕)
You would have to use fgetc to get a letter at a time until you hit a word bountry then do something with the word. Example
$fp = fopen("file.txt", "r");
$wordBoundries = array("\n"," ");
$wordBuffer = "";
while ($c = fgetc($fp)){
if (in_array($c, $wordBountries)){
// do something then clear the buffer
doSomethingWithBuffer($wordBuffer);
$wordBuffer = "";
} else {
// add the letter to the buffer
$wordBuffer.= $c;
}
}
fclose($fp);
You can try fget() function which read file line by line and when you get one line from file you use explode() to extract word from line which separated by space.
Try this code:
$handle = fopen("inputfile.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
// process the line read.
$word_arr = explode(" ", $line); //return word array
foreach($word_arr as $word){
echo $word; // required output
}
}
fclose($handle);
} else {
// error while opening file.
echo "error";
}
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 want to parse a comma separated value string into an array. I want to try the str_getcsv() php function but I can't find any good examples on how to use it.
For example I have an input where users submit tags for programming languages (php, js, jquery, etc), like the "tags" input in stackoverflow when you submit a question.
How would I turn an input with example value="php, js, jquery" into an array using str_getcsv?
Its true that the spec at http://us3.php.net/manual/en/function.str-getcsv.php doesn't include a standard example, but the user-submitted notes do a decent job of covering it. If this is a form input:
$val = $_POST['value'];
$data = str_getcsv($val);
$data is now an array with the values. Try it and see if you have any other issues.
I think you should maybe look at explode for this task.
$values = "php, js, jquery";
$items = explode(",", $values);
// Would give you an array:
echo $items[0]; // would be php
echo $items[1]; // would be js
echo $items[2]; // would be jquery
This would probably more efficient than str_getcsv();
Note that you would need to use trim() to remove possible whitespace befores and after item values.
UPDATE:
I hadn't seen str_getcsv before, but read this quote on the manpage that would make it seem a worthwhile candidate:
Why not use explode() instead of str_getcsv() to parse rows?
Because explode() would not treat possible enclosured parts of
string or escaped characters correctly.
For simplicity and readability, I typically find myself using just explode(), only adding in str_getcsv() if the following two conditions are met: 1) the primary delimiter is also used within the data itself; 2) the token that I'm trying to use as the main delimiter is enclosed by another distinct character.
For example, a basic parser for a CSV file:
$filename = $argv[1];
if (empty($filename)) { echo "Input file required\n"; exit; }
$AccountsArray = explode("\n", file_get_contents($filename));
As long as each of the elements of $AccountsArray doesn't embed a "," within the data itself, this will work perfectly and is straightforward and easy to follow:
foreach ($AccountsArray as $entry) {
$acctArr = explode(",", $entry);
}
However, often the data will contain the delimiter, at which point an enclosing token (a " in this example) has to be present. If so, then I switch to str_getcsv() like so:
foreach ($AccountsArray as $entry) {
$acctArr = str_getcsv($entry, ",", "\"");
}
//get the csv
$csvFile = file_get_contents('test.csv');
//separate each line
$csv = explode("\n",$csvFile);
foreach ($csv as $csvLine) {
//separet each fields
$linkToInsert = explode(",",$csvLine);
//echo what you need
//$linkToInsert[0] would be the first field, $linkToInsert[1] second field, etc
echo '• ' . $linkToInsert[1] . '<br>';
}
The code is quite simple, using the Str_getcsv function, we will go
through each line of the CSV file "images.csv" that is located in the
same directory as our script.
NOTE: Functions used are compatible with versions of PHP >= 5.3.0
//First, reading the CSV file
$csvFile = file('file.csv');
foreach ($csvFile as $line) {
$url = str_getcsv($line);
$ch = curl_init($url[0]);
$name = basename($url[0]);
if (!file_exists('directory/' . $name)) {
$fp = fopen('directory/' . $name, 'wb');
}
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
}