I been working trying everything to get this to work any help would be greatly apreciated.
i tried many couple of ways to get this work but i either get this error that the domain ame parameter is empty or I get the last domain in the txt file.
the txt file is just one domain per line.
$address="file.txt";
$shit=fopen($address,"r");
$contents2= fread($shit,filesize($address));
//also tried $domainlist=explode("\n\r",$contents2);
$domainlist=explode("\n",$contents2);
for($i=0 ; $i<=count($domainlist); ++$i){
$domainlist[$i]=$domain;
$contents = file_get_contents("http://www.whoisxmlapi.com/whoisserver/WhoisService?
domainName=$domain&username=$username&password=$password&outputFormat=JSON");
$results=json_decode($contents);
print_r($results);
unset($domain);
};
?>
Easier:
$lines = file("file.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach($lines as $domain) {
$contents = file_get_contents("http://www.whoisxmlapi.com/whoisserver /WhoisService?domainName=$domain&username=$username&password=$password&outputFormat=JSON");
$results = json_decode($contents);
print_r($results);
}
You may want to trim($domain) or make sure it's valid or other checks before doing file_get_contents().
$file = fopen("file.txt", "r");
while(!feof($file)){
$line = fgets($file);
$last_line = $line;
}
fclose($file);
echo $last_line;
A few ways to do this...
$file = file("file.txt");
foreach($file as $line) {
// do something with the $line
}
I prefer this method unless you're unsure of the file size. If unsure, you may want to consider using fopen.
Related
The numbers in my file are 5X5:
13456
23789
14789
09678
45678
I'm trying to put it into this form
array[0]{13456}
array[1]{23789}
array[2]{14789}
array[3]{09678}
array[4]{45678}
My code is:
$fileName = $_FILES['file']['tmp_name'];
//Throw an error message if the file could not be open
$file = fopen($fileName,"r") or exit("Unable to open file!");
while ($line = fgets($file)) {
$digits .= trim($line);
$members = explode("\n", str_replace(array("\r\n","\n\r","\r"),"\n",$digits));
echo $members;
The output I'm getting is this:
ArrayArrayArrayArrayArray
fgets gets a line from the file pointer, so theoretically there should be no "\r" or "\n" characters in $line. explode will still work, even if the delimiter is not found. You'll just end up with an array with one item, the entire string. You can't echo an array, though. (That's why you're seeing Array for each line; it's the best PHP can do when you use echo on an array.)
If I were you, I would rather just use file() instead.
$members = array_map('trim', file($fileName, FILE_IGNORE_NEW_LINES));
With the example file you showed, this should result in
$members = ['13456', '23789', '14789', '09678', '45678'];
You can simply put the lines into an array and use print_r instead of echo to print that array
while ($line = fgets($file)) {
$members[] = $line;
}
print_r($members);
It should depend on the file that you are dealing with.
FileType:
text -> fgets($file)
CSV -> fgetcsv($file)
I'm completely puzzled where to even start on this, but I need to provide a list of keywords in file A and then the same in list B.
With these too files I want to append the lines in A foreach line in file B
For example:
File A:
line1
line2
line3
File B:
test1
test2
test3
Output to a combined.txt file:
line1test1
line2test1
line3test1
line1test2 ... and so on
If you could provide me the portions of the script to research, a sample script, or even a working way to do it. I would greatly appreciate it.
Per request, here is my sample code:
<?php
$file1 = 'keywords.txt';
$file2 = 'topics.txt';
$combined = 'combined.txt';
$keywords = fopen("keywords.txt", "rb");
$topics = fopen("topics.txt", "rb");
$front = explode($topics);
$back = explode($topics);
while (!feof($keywords) ) {
file_put_contents($combined, . $front ."". $back . "\n");
fclose($keywords & $topics);
}
?>
Hope this helps. Comments are sprinkled throughout the code, which I hope is sufficient explanation as to what I'm doing.
<?php
// Open keywords file for reading
$keywords_file = 'keywords.txt';
$keywords_fh = fopen($keywords_file, 'r');
// Get line by line from keywords file, push into $keywords array
// Make sure to trim each line from fgets, to strip off \n at end.
$keywords = array();
while ($line = trim(fgets($keywords_fh))) {
array_push($keywords, $line);
}
fclose($keywords_fh);
// Open topics file for reading
$topics_file = 'topics.txt';
$topics_fh = fopen($topics_file, 'r');
// Get line by line from topics file, push into $topics array
// Make sure to trim each line from fgets, to strip off \n at end.
$topics = array();
while ($line = trim(fgets($topics_fh))) {
array_push($topics, $line);
}
fclose($topics_fh);
// Open combined file for writing
$combined_file = 'combined.txt';
$combined_fh = fopen($combined_file, 'w');
// Iterate through each keyword.
// For each iteration, iterate through each topic.
// Write the concatenation of keyword and topic to file.
foreach ($keywords as $keyword) {
foreach ($topics as $topic) {
fwrite($combined_fh, "$keyword$topic\n");
}
}
fclose($combined_fh);
Here are some links to PHP documentation for some of the key functions I used:
fopen
trim
fgets
fwrite
fclose
$f1 = explode("\n",file_get_contents("fileA.txt"));
$f2 = explode("\n",file_get_contents("fileB.txt"));
foreach ($f1 as $key => $value) {
$f3[] = $value.$f2[$key];
}
file_put_contents("fileC.txt", implode("\n",$f3));
Okay so I have a text file and inside of the text file I have these lines:
IP = 127.0.0.1
EXE = Client.exe
PORT = 8080
TITLE = Title
MAINT = False
MAINT-Message = This is the message.
what I am wanted to do is get the 'False' part on the fifth line.
I have the basic concept but I can't seem to make it work. This is what I have tried:
<?php
$file = file_get_contents('LauncherInfo.txt');
$info = explode(' = ', $file);
echo $info[5];
?>
And with this I get a result but when I echo $info[5] it gives me 'False Maint-Message' so it splits it but it only splits at the = sign. I want to be able to make it split at the where I have pressed enter to go onto the next line. Is this possible and how can I do it?
I was thinking it would work if I make it explode on line one and then do the same for the second line with a loop until it came to the end of the file? I don't know how to do this though.
Thanks.
I think you're looking for the file(), which splits a file's contents into an array of the file's lines.
Try this:
$file = file('LauncherInfo.txt');
foreach ($file as $line) {
if ($line) {
$splitLine = explode(' = ',$line);
$data[$splitLine[0]] = $splitLine[1];
}
}
echo $data['MAINT'];
Just in case you were curious, since I wasn't aware of the file() function. You could do it manually like this
<?php
$file = file_get_contents('LauncherInfo.txt');
$lines = explode("\n", $file);
$info=array();
foreach($lines as $line){
$split=explode(' = ',$line);
$info[]=$splitline[1];
}
echo $info[5];//prints False
?>
I'm trying to read a specific line from a text file using php.
Here's the text file:
foo
foo2
How would I get the content of the second line using php?
This returns the first line:
<?php
$myFile = "4-24-11.txt";
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
echo $theData;
?>
..but I need the second.
Any help would be greatly appreciated
$myFile = "4-24-11.txt";
$lines = file($myFile);//file in to an array
echo $lines[1]; //line 2
file — Reads entire file into an array
omg I'm lacking 7 rep to make comments. This is #Raptor's & #Tomm's comment, since this question still shows up way high in google serps.
He's exactly right. For small files file($file); is perfectly fine. For large files it's total overkill b/c php arrays eat memory like crazy.
I just ran a tiny test with a *.csv with a file size of ~67mb (1,000,000 lines):
$t = -microtime(1);
$file = '../data/1000k.csv';
$lines = file($file);
echo $lines[999999]
."\n".(memory_get_peak_usage(1)/1024/1024)
."\n".($t+microtime(1));
//227.5
//0.22701287269592
//Process finished with exit code 0
And since noone mentioned it yet, I gave the SplFileObject a try, which I actually just recently discovered for myself.
$t = -microtime(1);
$file = '../data/1000k.csv';
$spl = new SplFileObject($file);
$spl->seek(999999);
echo $spl->current()
."\n".(memory_get_peak_usage(1)/1024/1024)
."\n".($t+microtime(1));
//0.5
//0.11500692367554
//Process finished with exit code 0
This was on my Win7 desktop so it's not representative for production environment, but still ... quite the difference.
If you wanted to do it that way...
$line = 0;
while (($buffer = fgets($fh)) !== FALSE) {
if ($line == 1) {
// This is the second line.
break;
}
$line++;
}
Alternatively, open it with file() and subscript the line with [1].
I would use the SplFileObject class...
$file = new SplFileObject("filename");
if (!$file->eof()) {
$file->seek($lineNumber);
$contents = $file->current(); // $contents would hold the data from line x
}
you can use the following to get all the lines in the file
$handle = #fopen('test.txt', "r");
if ($handle) {
while (!feof($handle)) {
$lines[] = fgets($handle, 4096);
}
fclose($handle);
}
print_r($lines);
and $lines[1] for your second line
$myFile = "4-21-11.txt";
$fh = fopen($myFile, 'r');
while(!feof($fh))
{
$data[] = fgets($fh);
//Do whatever you want with the data in here
//This feeds the file into an array line by line
}
fclose($fh);
This question is quite old by now, but for anyone dealing with very large files, here is a solution that does not involve reading every preceding line. This was also the only solution that worked in my case for a file with ~160 million lines.
<?php
function rand_line($fileName) {
do{
$fileSize=filesize($fileName);
$fp = fopen($fileName, 'r');
fseek($fp, rand(0, $fileSize));
$data = fread($fp, 4096); // assumes lines are < 4096 characters
fclose($fp);
$a = explode("\n",$data);
}while(count($a)<2);
return $a[1];
}
echo rand_line("file.txt"); // change file name
?>
It works by opening the file without reading anything, then moving the pointer instantly to a random position, reading up to 4096 characters from that point, then grabbing the first complete line from that data.
If you use PHP on Linux, you may try the following to read text for example between 74th and 159th lines:
$text = shell_exec("sed -n '74,159p' path/to/file.log");
This solution is good if your file is large.
You have to loop the file till end of file.
while(!feof($file))
{
echo fgets($file). "<br />";
}
fclose($file);
Use stream_get_line: stream_get_line — Gets line from stream resource up to a given delimiter
Source: http://php.net/manual/en/function.stream-get-line.php
You could try looping until the line you want, not the EOF, and resetting the variable to the line each time (not adding to it). In your case, the 2nd line is the EOF. (A for loop is probably more appropriate in my code below).
This way the entire file is not in the memory; the drawback is it takes time to go through the file up to the point you want.
<?php
$myFile = "4-24-11.txt";
$fh = fopen($myFile, 'r');
$i = 0;
while ($i < 2)
{
$theData = fgets($fh);
$i++
}
fclose($fh);
echo $theData;
?>
I like daggett answer but there is another solution you can get try if your file is not big enough.
$file = __FILE__; // Let's take the current file just as an example.
$start_line = __LINE__ -1; // The same with the line what we look for. Take the line number where $line variable is declared as the start.
$lines_to_display = 5; // The number of lines to display. Displays only the $start_line if set to 1. If $lines_to_display argument is omitted displays all lines starting from the $start_line.
echo implode('', array_slice(file($file), $start_line, lines_to_display));
I searched for a one line solution to read specific line from a file.
Here my solution:
echo file('dayInt.txt')[1]
Let say a text file contain
Hello everyone, My name is Alice, i stay in Canada.
How do i use php to find "Alice" and replace it with "John".
$filename = "C:\intro.txt";
$fp = fopen($filename, 'w');
//fwrite($fp, $string);
fclose($fp);
$contents = file_get_contents($filename);
$new_contents = str_replace('Alice', 'John', $contents);
file_put_contents($filename, $new_contents);
Read the file into memory using fread(). Use str_replace() and write it back.
If its a big file, use iteration instead of reading all into memory
$f = fopen("file","r");
if($f){
while( !feof($f) ){
$line = fgets($f,4096);
if ( (stripos($line,"Alice")!==FALSE) ){
$line=preg_replace("/Alice/","John",$line);
}
print $line;
}
fclose($f);
}