this code not display title when i get link from txt file
<?php
function page_title($url) {
$fp = file_get_contents($url);
if (!$fp)
return null;
$res = preg_match("/<title>(.*)<\/title>/siU", $fp, $title_matches);
if (!$res)
return null;
// Clean up title: remove EOL's and excessive whitespace.
$title = preg_replace('/\s+/', ' ', $title_matches[1]);
$title = trim($title);
return $title;
}
$file = fopen("link.txt","r");
$lien = fgets($file);
fclose($file);
print page_title($lien);
?>
this code not display title when i get link from txt file
blank screen
my link.txt countains :
http://google.com
When I run this code i get the word "Google" displayed on my screen. So i have to think that your code is doing what you want but that there is some other, perhaps host-specific, problem here.
OK I just broke it by putting a CR in the text file after the URL and I fixed it by changing
$lien = fgets($file);
to
$lien = trim(fgets($file));
Related
So, I have a PHP script that is supposed to download images that the user inputs. However, if the user uploads a TXT file and it contains direct links to images, it should download the images from all the URLs in the file. My script seems to be working, although it seems that only the last file is downloaded while the others are stored as files containing no data.
Here's the portion of my script where it parses the TXT
$contents = file($file_tmp);
$parts = new SplFileObject($file_tmp);
foreach($parts as $line) {
$url = $line;
$dir = "{$save_loc}".basename($url);
$fp = fopen ($destination, 'w+');
$raw = file_get_contents($url);
file_put_contents($dir, $raw);
}
How do I make it download every URL from the TXT file?
When you iterate over an SplFileObject, you get the whole line, including whitespace. Your URL will thus be something like
http://example.com/_
(php seems to mangle the newline to an underscore) and thus you'll get an error for many URLs (some URLs will still work fine, since they contain the important information prior. For instance, Batch download URLs in PHP? works, but https://stackoverflow.com/_ does not). If an error occurs, file_get_contents will return false, and file_put_contents will interpret that like an empty string.
Also, the line $fp = fopen ($destination, 'w+'); is really strange. For one, since $destination is not defined, it would error anyways. Even if $destination is defined, you'll end up with lots of file handles and overwrite that poor file multiple times. You can just remove it.
To summarize, your code should look like
<?php
$file_tmp = "urls.txt";
$save_loc = "sav/";
$parts = new SplFileObject($file_tmp);
foreach($parts as $line) {
$url = trim($line);
if (!$url) {
continue;
}
$dir = "{$save_loc}".basename($url);
$raw = file_get_contents($url);
if ($raw === false) {
echo 'failed to donwload ' . $url . "\n";
continue;
}
file_put_contents($dir, $raw);
}
It looks like line
$parts = new SplFileObject($file_tmp);
isn't necessary as well as
$fp = fopen ($destination, 'w+');
file() function reads entire file into array. You just have call trim() on each array element to remove new line from characters. Following code should work properly:
<?php
$save_loc = './';
$urls = file('input.txt');
foreach($urls as $url) {
$url = trim($url);
$destination = $save_loc . basename($url);
$content = file_get_contents($url);
if ($content) {
file_put_contents($destination, $content);
}
}
i tried to search, but still dont know the solution at all, for my next PHP code.
<?php
$city="Budapest"; // Your city
$country="hu"; // Two digit country code
$url="http://api.openweathermap.org/data/2.5/weather?q=".$city.",".$country."&appid=2de143494c0b295cca9337e1e96b00e0&units=metric";
$json=file_get_contents($url);
$data=json_decode($json,true);
$file = '/home/cs2d/sys/lua/weather.dat';
$current = file_get_contents($file);
$current .= $data['weather'][0]['main']."\n".$data['main']['temp']."\n";
// Write the contents back to the file
file_put_contents($file, $current);
?>
As you can see it's a simple code, which write values into the weather.dat file.
But how to possible to do that its just refresh lines instead of add new one.
Any idea?
This works :
$city="Budapest"; // Your city
$country="hu"; // Two digit country code
$url="http://api.openweathermap.org/data/2.5/weather?q=".$city.",".$country."&appid=2de143494c0b295cca9337e1e96b00e0&units=metric";
$json=file_get_contents($url);
$data=json_decode($json,true);
$file = 'weather.dat';
$current = file_get_contents($file);
$contents = file_get_contents($file);
echo $current;
$contents = str_replace($current, ' ', $contents);
echo $contents;
file_put_contents($file,$contents);
$current = file_get_contents($file);
$current .= $data['weather'][0]['main']."\n".$data['main']['temp']."\n";
// Write the contents back to the file
file_put_contents($file, $current);
A (simple) question.
I have a TXT file search script in PHP.
$search = $_GET["search"];
$logfile = $_GET['logfile'];
// Read from file
$file = fopen($logfile, "r");
?> <head> <title>Searching: <?php echo $search ?></title> </head> <?php
while( ($line = fgets($file) )!= false)
{
if(stristr($line,$search)) // case insensitive
echo "<font face='Arial'> $line </font><hr>";
}
fclose($file);
Now what I want to do is delete all the text it finds in the TXT file.
I tried doing a str_replace but it didn't work.
Thanks for helping!
I think this will do the magic:
$file->ftruncate($file->ftell());
You need to gather the lines which doesn't contain the search term and you need to save the text in an array.
When you're done with the listing, you need to open the file in write mode (which will empty the file) and then write the text you gathered in the file.
Here's the code:
<?php
$search = isset($_GET["search"]) ? $_GET["search"] : '';
$logfile = isset($_GET['logfile']) ? $_GET['logfile'] : '';
$text_without_term_arr = array();
if(!empty($logfile) && !empty($search)){
// Read from file
$file = fopen($logfile, "r");
echo ' <head>
<title>Searching: ' . $search . '</title>
</head>';
while(($line = fgets($file))!== false){
if(stristr($line, $search)){
// Case insensitive search
echo '<font face="Arial">' . $line . '</font><hr/>';
} else {
// Search term not found in these lines
array_push($text_without_term_arr, $line);
}
}
fclose($file);
// Empty the file and write the text again without the search term
if(!empty($text_without_term_arr)){
$new_file = fopen($logfile, "w");
$content = implode("\n", $text_without_term_arr);
fwrite($new_file, $content);
fclose($new_file);
}
}
?>
You need another file handle to write the result out to:
$tempname=tmpname('/tmp','result');
$outfile=fopen($tempname,'w');
Next, use str_ireplace to remove the found text in each line:
$newline=str_ireplace($search, '', $line);
Then write the new line out to the out file:
fputs($outfile,$newline); // May need to send PHP_EOL too
Close the file off:
fclose($outfile);
And then rename the new file to the old filename:
rename($tempname,$logfile);
I am using PHP to read a simple text file with the fgets() command:
$file = fopen("filename.txt", "r") or exit('oops');
$data = "";
while(!feof($file)) {
$data .= fgets($file) . '<br>';
}
fclose($file);
The text file has leading white spaces before the first character of each line. The fgets() is not grabbing the white spaces. Any idea why? I made sure not to use trim() on the variable. I tried this, but the leading white spaces still don't appear:
$data = str_replace(" ", " ", $data);
Not sure where to go from here.
Thanks in advance,
Doug
UPDATE:
The text appears correctly if I dump it into a textarea but not if I ECHO it to the webpage.
Function fgets() grabs the whitespaces. I don't know what you are exactly doing with the $data variable, but if you simply display it on a HTML page then you won't see whitespaces. It's because HTML strips all whitespaces. Try this code to read and show your file content:
$file = fopen('file.txt', 'r') or exit('error');
$data = '';
while(!feof($file))
{
$data .= '<pre>' . fgets($file) . '</pre><br>';
}
fclose($file);
echo $data;
The PRE tag allows you to display $data without parsing it.
Try it with:
$data = preg_replace('/\s+/', ' ', $data);
fgets should not trim whitespaces.
Try to read the file using file_get_contents it is successfully reading the whitespace in the begining of the file.
$data = file_get_contents("xyz.txt");
$data = str_replace(" ","~",$data);
echo $data;
Hope this helps
I currently have the same requirement and experienced that some characters are written as a tab character.
What i did was:
$tabChar = ' ';
$regularChar = ' '
$file = fopen('/file.txt');
while($line = fgets($file)) {
$l = str_replace("\t", $tabChar, $line);
$l = str_replace(" ", $regularChar, $line);
// ...
// replacing can be done till it matches your needs
$lines .= $l; // maybe append <br /> if neccessary
}
$result = '<pre'> . $lines . '</pre>';
This one worked for me, maybe it helps you too :-).
I want to detect if a word in a text file exists, and then remove it.. so, this is my code:
<?php
$search = $id;
$lines = file("./user/".$_GET['own'].".txt");
// Store true when the text is found
$found = false;
foreach($lines as $line)
{
if(strpos($line, $search) !== false)
{
$found = true;
// open to read and modify
$file = "./user/".$_GET['own'].".txt";
$fh = fopen($file, 'r+');
$data = fread($fh, filesize($file));
$new_data = str_replace($id."\n", "", $data);
fclose($fh);
// Open to write
$fh = fopen($file, 'r+');
fwrite($fh, $new_data);
fclose($fh);
$status = "has been successfully deleted.";
}
}
// If the text was not found, show a message
if(!$found)
{
$status = "is not exist in your list.";
}
?>
I got this work hours before.. I did some changes to my script and somehow, it didnt work anymore.. can anyone see through the code and tell me what is wrong??
or can anybody give simpler way to do what I want?? my code is messed..
I want to detect if a word in a text file exists, and then remove it..
<?php
$search = $id;
$filename="./user/".$_GET['own'].".txt";
$contents = file_get_contents($filename);
$contents = str_replace($id."\n", "", $contents);
file_put_contents($filename,$contents);
?>
That is all that there is to it.
Edit:
To make this equivalent to your solution, one can use
<?php
$search = $id;
$filename="./user/".$_GET['own'].".txt";
$contents = file_get_contents($filename);
$contents = str_replace($id."\n", "", $contents,$count);
if($count>0)
{
file_put_contents($filename,$contents);
echo "found and removed";
}
else
{
echo "not found";
}
?>