php set lines in a text file to an array value - php

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;
}

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

Read serialized file, record by record

I save to file data from form:
$name = $_POST['name'];
$url = $_POST['url'];
$comm = $_POST['comm'];
$data["name"]=$name;
$data["url"]=$url;
$data["comm"]=$comm;
file_put_contents("db.txt", serialize($data));
Now, I would like to read this file record by record.
$file_handle = fopen("db.txt", "r");
while (!feof($file_handle)) {
$line = fgets($file_handle);
$arr = unserialize($line);
var_dump($arr);
}
fclose($file_handle);
But this code read only last record. How to read all file?
Replace file_put_contents("db.txt", serialize($data)); to
file_put_contents("db.txt", PHP_EOL .serialize($data), FILE_APPEND);
file_put_contents("db.txt", serialize($data));// will over write the file again and again. so you cant able to read all the data. FILE_APPEND helps to append the data And PHP_EOL helps to leave a line breake.
Hi i try this code for your solution:
<?php
$name = "rdn";
$url = "http://google.it";
$comm = "com";
$data["name"]=$name;
$data["url"]=$url;
$data["comm"]=$comm;
file_put_contents("db.txt", serialize($data)."\n",FILE_APPEND);
$fh = fopen('db.txt','r');
while ($line = fgets($fh)) {
// <... Do your work with the line ...>
var_dump(unserialize($line));
}
fclose($fh);
?>
without "\n" don't work!

Why is str_replace not working correctly

In my directory I have a list.csv of the form:
RP2015, active
Hope, paused
Process99, active
I'm writing a php script to allow a web user to switch the different lines from 'active' to 'paused' and back. Unfortunately I've hit a snag. My current code is live at: http://whitewaterwriters.com/Driver/index.php
and it looks like this
<HTML>
<Body>
<?
if ($_POST != null) {
$target = $_POST ['sprint'];
echo "<br>Target was:".$target;
$replacement=str_replace('active','paused',$target);
if (strpos($target,'paused') !== false) {
$replacement=str_replace('paused','active',$target);
}
echo "<br>Replacement was:".$replacement."<br>";
$filename = "list.csv";
$contents = file_get_contents($filename);
print "<br>contents was:".$contents;
$new_contents = str_replace($target, $replacement, $contents);
print "<br>contents became:".$new_contents;
file_put_contents($filename, $new_contents);
}
?>
<br><br>
<?php
$row = 1;
if (($handle = fopen("list.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
echo '<form action="index.php" method=post>';
echo $data[0] . $data[1];
echo '<button type="submit" value="'. $data[0].", ".$data[1].'" name="sprint">Pause</button></form><br>';
}
fclose($handle);
}
?>
</body>
</html>
For some reason the replace is not firing. The event is captured, the correct target and replace strings are (I think) generated, but the replace is NOT coming out. The output I get is:
Target was:RP2015, active
Replacement was:RP2015, paused
contents was:RP2015, active
contents became:RP2015, active
RP2015 active
Can anyone tell me what's going on?
EDIT:
The current list.csv is exactly:
RP2015, active
`
Try this:-
$fp = fopen($filename, "wb");
$handle = fopen($filename, "wb");
$replacement = str_replace("active", "paused", $fp);
$numbytes = fwrite($handle, $replacement);
fclose($handle);
The thing I had forgotten is that html squashes consecutive spaces together which is why the $target looked like it was fine. Actually:
$data[0].", ".$data[1]
only needed to be
$data[0].",".$data[1]
Because there was a space left over from the csv parsing. I'll make the code a bit more robust to that in future.
For the interested - this helper function I wrote helped me locate the error:
function toask($inStr){
$arr1 = str_split($inStr);
foreach ( $arr1 as $a){
print ord($a)." ";
}
}
It converts a string to a sequence of ascii codes do you can make sure, for example, that quote characters are the ones you think they are...

How can I add multiple strings to one text file, and read the all?

I am trying to make a program where I can add things to a list, read things, and clear the list. I have the clear function working perfectly, however I can't seem to add or read more than 1 line at a time. I am using fwrite($handle, $MyString); but that replaces everything in the entire file with $MyString. To get the information from the file I am using $list = fgets($handle); and then using echo to print it. This reads the first line in the file only.
Any help?
Thanks!
Getlist code:
<?php
$myFile = "needlist.txt";
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
echo $theData;
?>
Add to the list code:
<?php
$neededlist = "needlist.txt";
$fh = fopen($neededlist, 'w');
$user_message = $_REQUEST['txtweb-message'];
$needed .= $user_message;
$needed .= "\n";
fwrite($fh, $needed);
fclose($fh);
echo "You have successfully added ", $user_message;
?>
When you write to the file are you opening your filehandle with the "a" mode option? Opening with "w" or "x" truncates it so you start with a clean file (http://php.net/fopen)
fgets(); reads only until the end of the line ( http://php.net/fgets ). To get the whole file you can try:
var $list = "";
var $line = "";
while ($line = fgets($handle)) {
$list = $list . "\n" . $line;
}
echo $list;
You want to add the "\n" because fread doesn't read the linefeeds IIRC. There're also a couple functions that might be more appropriate in this situation like file_get_contents and fread.
Fgets returns only one string. You should use it in cycle like that:
while (($buffer = fgets($handle, 4096)) !== false) {
echo $buffer;
}

PHP get array of words from txt file

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

Categories