PHP get array of words from txt file - php

I have a text file with spam words. I want to have an array filled with those words.
I've tried doing:
$fp = #fopen("../files/spam.txt",'rb');
$words = fgetcsv($fp,100,"\n");
but it doesn't work (words only has the first letter of the txt file in it first cell).
do you how to do this?
EDIT:
the .txt file looks like this:
yahoo
google
msn
blah
blah
EDIT:
I DONT KNOW WHAT IS A CSV FILE! THIS IS A TEXT FILE! I JUST GIVE AN EXAMPLE.
please could some1 help me it looks really easy, i just dont understand.

That is not a CSV file. CSV stands for comma separated values. You have no commas!
$spam_words = file('../files/spam.txt', FILE_IGNORE_NEW_LINES);

All you need to do is:
$words = file('./files/spam.txt',FILE_IGNORE_NEW_LINES);

$artic = array(); //create a array
$directory = "/var/www/application/store/"; //define path
$files1 = scandir($directory); //scan the directory
$c = count($files1); //count the files the directory
print $c; //print it
for($i = 2; $i < $c; $i++) {
print "<br />" . $files1[$i];
$f = $directory . $files1[$i];
print $f . "<br />";
$h = fopen($f, 'r') or die("cannot open a file!!". $f);
$line1 = fgets($h);
list($id, $idval) = explode("\t\t", $line1);
print "$id";
}

How about splitting the string you read from the file into an array?
split() function definition.
$string = "Niagara Becks Corn";
$array = split(" ", $string);
# ["Niagara", "Becks", "Corn"]

Use the 'file' function to read a PHP file from the disk into an array. See the manual here: http://php.net/manual/en/function.file.php

Try this
$file = file_get_contents('spam.txt');
$file_words = explode(" ", $file);
$file_count = count($file_words);
for ($i=0; $i < $file_count; $i++){
echo $file_words[$i] . "<br />";
}
Your spam.txt file should look like this:
yahoo msn google

Related

how can I sort a text file in php

english, lang1, lang2
rat, rat_lang1, rat_lang2
ball, ball_lang1, ball_lang2
air, air_lang1, air_lang2
If I have this text file I read in php, how can I sort it starting the second line, the first line being the heading of the file. So that the file will print out like..
english....
air....
ball...
rat....
I read the file using fopen, put it in $content using fread, used explode with new line. I can see the array of lines but cannot figure out how to sort it. Any suggestions would be appreciated.
Much of this solution was answered within the comments in response to your question. All put together you're looking for something like:
<?php
$f = file("text.txt"); //read the text file into an array
$newf = fopen("newtext.txt", "w+"); //open another file
$header = $f[0]; //store the first element of the array as $header
echo $header."<br>"; //and echo the header
fwrite($newf, $header); //write the header to the new file
array_shift($f); //then remove the first element of the array i.e. the header
sort($f); //sort the array (no flag param = alphabetical sort)
foreach($f as $line){ //loop through the sorted array
echo $line."<br>"; //print each element as it's own line
fwrite($newf, trim($line)."\n"); //write other elements to new file on own line
}
fclose($newf); //close the file
?>
Try this:
$data = trim(file_get_contents('sort_test.txt'));
$data = explode("\n", $data);
$array_order = array();
$fileLocation = getenv("DOCUMENT_ROOT") . "/myfile.txt";
$file = fopen($fileLocation, "w");
for ($i = 0; $i < count($data); $i++) {
($i > 0) ? $array_order[$i] = $data[$i] : fwrite($file, $data[0]);
}
sort($array_order);
$data = implode("\n", $array_order);
fwrite($file, $data);
fclose($file);
echo 'file created - location::' . $fileLocation;
Output myfile.txt
english, lang1, lang2
air, air_lang1, air_lang2
ball, ball_lang1, ball_lang2
rat, rat_lang1, rat_lang2
Maybe the new file (myfile.txt) will needs write permission to the directory you are writing to , in my case the file has been stored into C:/.../htdocs/myfile.txt

php set lines in a text file to an array value

Im looking to do something like the following
$file = ('file.txt');
$fopen($file);
then read each line from the file individually and set it as a specific array
like so
read $file get $line1 set as $array[0]
read $file get $line2 set as $array[1]
read $file get $line3 set as $array[2]
I would like to use these arrays created from the lines on the text file IN PLAIN TEXT like this:
$urlout = file_get_contents("http://myurl.com/?=$line1");
echo $urlout;
$urlout2 = file_get_contents("http://myurl.com/?=$line2");
echo $urlout2;
$urlout3 = file_get_contents("http://myurl.com/?=$line3");
echo $urlout3;
So if the array were 123.22.11.22 the link would look like this:
$line1 = array[0] (123.22.11.22)
$urlout = file_get_contents("http://myurl.com/?=$line1");
echo $urlout;
and the result would be
Info for 123.22.11.22
more info
some more
Modified answer as per the change indicated by the user :
Reading 2 lines on each loop..
$lines = file("file.txt");
for($i=0 ; $i<count($lines); $i=($i+2) )
{
echo file_get_contents("http://myurl.com/?=".$lines[$i]);
echo file_get_contents("http://myurl.com/?=".$lines[($i + 1)]);
}
Imp Note : A URL can be used as a filename with file_get_contents() function, only if the fopen wrappers have been enabled.
$handle = fopen("file.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
echo file_get_contents("http://myurl.com/?=$line");
}
fclose($handle);
}
The answer was to insert a "\n" separator upon inserting into the text file, then removing it after the first result was called
$lines = file("geo.txt");
for($i=0 ; $i<count($lines); $i=($i+2) )
{
echo file_get_contents("https://test.com/api/GEO.php?info=".$lines[$i]);
$lolz = file_get_contents("https://test.com/api/GEO.php?info=".$lines[($i + 1)]);
$lolz = str_replace(" \n", '', $lolz);
echo "<br>".$lolz;
}

changing new line to <br> in text area

My problem is pretty simple. I want to change new lines in text area to <br> tags BUT I need the final string to be one-line text. I tried using nl2br function but as a result I get string with <br> tags and new lines. I also tried to simply replace &#013 or &#010 symbols with <br> using str_replace but it doesn't work.
Here is sample of my latest code:
Godziny otwarcia: <textarea name="open" rows="3" cols="20">'."$openh".'</textarea>
<input type="submit" name="openb" value="Zmień"/><br>
if($_POST['openb']) {
$open = $_POST['open'];
str_replace('&#010', '<br>', $open);
change_data(21, $open);
}
The $openh is result of this:
$tab = explode('<br>', $openh);
$openh = null;
for($i=0;$i<count($tab);$i++)
$openh = $openh . $tab[$i] . '&#013';
(yes, I know i could use str_replace, don't ask why I did it this way)
and the original $openh is $openh = 'Pon-pt 9:00-17:00<br>Środa 12:00-17:00'
Also you may want to see my change_data function as it is connected to why i need the string to be in one line, so here it is:
function change_data($des_line, $data) {
$file = 'config.php';
$lines = file($file);
$i=1;
foreach($lines as $line_num => $line) {
$wiersz[$i] = $line;
$i++;
}
$change = explode("'", $wiersz[$des_line]);
$wiersz[$des_line] = $change[0] . "'" . $data . "'" . $change[2];
$i = 1;
$f = fopen($file, w);
while($i <= count($wiersz)) {
fwrite($f, $wiersz[$i]);
$i++;
}
fclose($f);
header('location: index.php?p=admin');
}
I'm not PHP specialist so sometimes I do things little "hard" way.. I had huge problems with reading file config.php line by line and these are results of my few-hours effort :(
have you tried the php constant PHP_EOL? in you str_replace code?
$open=str_replace(PHP_EOL,"<br>",$_POST["open"]);
There is a ready made PHP function for that named nl2br
Source: https://stackoverflow.com/a/16376133/469161

Can I add an image path from a .txt file in a webpage using PHP?

I need to dynamically add in the img src full file path to a file from a .txt file. So far i have been using the below code to populate titles, and descriptions:
< ?php
$myFile = "film_music/feature1.txt";
$lines = file($myFile);//file in to an array<br />
echo $lines[0]; //line 1
? >
The feature file contains all details for movies that will eventually be displayed here:
http://www.londonosophy.com/film_music2.php
Currently the file contains the following rows:
Sightseers (2012)
Dark comedy, featuring Alice Lowe
images/Sightseers-TinaPencil.jpg
Does anyone know php code that can read line X (or line 3 in this case) and dynamically populate the img src="" file path?
Many thanks in advance for your suggestions!
If you need to iterate over lines and need to check if line contains file path (for example, if sometimes there are white lines between blocks and sometimes they are missing), then:
<?php
$myFile = 'film_music/feature1.txt';
$lines = file($myFile);
$needle = 'images/';
$needleLen = strlen($needle);
foreach ($lines AS $line) {
$line = trim($line);
if (substr($line, 0, $needleLen) == $needle) {
echo '<img src="' . $line . '" alt="" />';
}
}
?>
You need to fetch 3rd line of the file every time, because it contains that path of the image.
<?php
global var $raw;
$myFile = "film_music/feature1.txt";
// open file...
$lines = file($myFile);//file in to an array<br />
for($i=2;$i<=no_of_lines;$i+3){
$raw = $lines[$i];
}
// Populate $raw variable where you need.
?>
Use $fh = fopen(...) and loop every line.
while (!feof($fh)) {
$line = fgets($fh);
if ($line === false) {
throw new Exception("File read error");
}
[do your things.]
}
http://www.php.net/manual/en/function.fopen.php
You can read each line of text line as:
$lines=file('file.txt');
$lines=array();
$fp=fopen('file.txt', 'r');
while (!feof($fp))
{
$line=fgets($fp);
//process line however you like
$line=trim($line);
//add to array
$lines[]=$line;
}
fclose($fp);
if you don't need any special processing, this should do what you're looking for
$lines = file($lines, FILE_IGNORE_NEW_LINES);
may this help you... :)
you can check all line of text file with in_array("you want", $lines) as you desire...if its not dynamically....

Sort the unsorted text file and rewrite to same text file in sorted order

I have a question. I am in process of learning how to read/write files, but having little trouble trying to do both at the same time in same php script. I have a text file with words like this,
Richmond,Virginia
Seattle,Washington
Los Angeles,California
Dallas,Texas
Jacksonville,Florida
I wrote a code to sort them in order and this will display in sort order by City.
<?php
$file = file("states.txt");
sort($file);
for($i=0; $i<count($file); $i++)
{
$states = explode(",", $file[$i]);
echo $states[0], $states[1],"<br />";
}
?>
From this, how can I rewrite those sorted information back into the states.txt file?
The easiest way to write the contents of $file back to the file would be using file_put_contents in collaboration with implode.
file_put_contents("states.txt", implode($file));
Try using fopen and fwrite.
$fileWrite = fopen("filePah", "w");
for($i=0; $i<count($file); $i++)
{
fWrite($fileWrite, $file[i]);
}
fClose($fileWrite);
<?php
$file = file("states.txt");
sort($file);
$newContent = "";
for($i=0; $i<count($file); $i++)
{
$states = explode(",", $file[$i]);
$newContent .= $states[0] .', '. $states[1] . PHP_EOL;
}
file_put_contents('states.txt',$newContent);
?>
PHP: file_put_contents
Try something like this:
$fo = fopen("filename", "w");
$content = "";
for ($i = 0; $i < count($file); $i++) {
$states = explode(",", $file[$i]);
$content .= $states[0] . "," . $states[1] . "\n";
}
fwrite($fo, $content);
fclose($fo);
this is a little extended, however I thought it might be useful to smb. I have an m3u playlist and need only particular rows filtered, sorted and printed. Credits go to Devil:
<?php
//specify that the variable is of type array
$masiv = array();
//read the file
$file = '/home/zlobi/radio/pls/all.m3u';
$f = fopen($file, "r");
while ($line = fgets($f))
{
//skip rows with #EXT
if(strpos($line, "#EXT") !== false) continue;
$text = str_replace('.ogg', ' ', $line);
$text = str_replace('/home/zlobi/radio/',' ',$text);
//add the song as an element in an array
$masiv[] = $text;
}
$f = fclose($f);
//sort the array
sort($masiv);
//pass via the array, take each element and print it
foreach($masiv as $pesen)
print $pesen.'<br/>';
?>
masiv is array, pesen is song in Bulgarian :)
CAPital letters are sorted first.
Regads
Once you are done reading the file into the array by a call to file. You can open the file for writing by using the fopen function, write into the file using the fwrite and close the file handle using fclose:
<?php
$file = file("states.txt"); // read file into array.
$fh = fopen('states.txt','w') or die("..."); // open same file for writing.
sort($file);
for($i=0; $i<count($file); $i++)
{
$states = explode(",", $file[$i]);
echo $states[0], $states[1],"<br />";
fwrite($fh,"$states[0],$states[1] <br />"); // write to file.
}
fclose($fh); // close file.
?>
Open the file, write to it, close it (this assumes $file is the variable from your code):
$fp = fopen('states.txt', 'w');
for($i=0; $i<count($file); $i++)
fwrite($fp, $file[$i]);
}
fclose($fp);
And see http://php.net/manual/en/function.fwrite.php
This is by far the fastest and most elegant solution that I have found, when I had the same problem.
If you're on Linux (with exec allowed in PHP configuration) you can do the following (provided you want to sort files numerically):
exec("sort -n " . $pathToOriginalFile . " > " . $pathToSortedFile);
Basically, execute bash command sort that sorts the lines in a file numerically.
If you want to keep the data in the original file do this:
exec("sort -n " . $pathToOriginalFile . " > " . $pathToSortedFile);
exec("rm " . $pathToOriginalFile);
exec("mv " . $pathToSortedFile . " " . $pathToOriginalFile);
If you want an alphabetical sort just exclude -n (--numeric-sort) option.
exec("sort " . $pathToOriginalFile . " > " . $pathToSortedFile);
For me the command took about 3 seconds to sort 10 million lines in the file on the server.
You can find more about sort here http://www.computerhope.com/unix/usort.htm
Hope it helps.

Categories