Reputation: 41
I have the following codes:
require("class.XMLHttpRequest.php");
function hot($news){
$url="https://localhost/search.aspx?search=".$news."";
$ajax=new XMLHttpRequest();
$ajax->setRequestHeader("Cookie","Cookie: host");
$ajax->open("GET",$url,true);
$ajax->send(null);
if($ajax->status==200){
$rHeader=$ajax->getResponseHeader("Set-Cookie");
if(substr_count($rHeader, "Present!")>0) { return true; }
}else{ return false; }
}
$content1= hot("britney") ? "britney found" : "";
$content2= hot("gaga") ? "gaga found" : "";
$content3= hot("carol") ? "carol found" : "";
$filename = 'result.txt';
$handle = fopen($filename, 'a');
fwrite($handle, "$Content1\r\n");
fwrite($handle, "$Content2\r\n");
fwrite($handle, "$Content3\r\n");
fwrite($handle, "$Content4\r\n");
fclose($handle);
i want to shorten the script cuz i have a lot of $ContentN variables maybe something like foreach ??
Upvotes: 0
Views: 524
Reputation: 43298
I would do it like this:
$celebrities = array('britney','gaga','carol');
$filename = 'result.txt';
$handle = fopen($filename, 'a');
foreach($celebrities as $celebrity)
{
if(hot($celebrity)) { fwrite($handle, "{$celebrity}\r\n"); }
}
fclose($handle);
If you need more celebrities, just add them to the array.
Upvotes: 3
Reputation: 706
Here's a brief code refactoring for you. Updated variable names, trending topics held in an array, and the foreach you asked about. Code is untested.
require("class.XMLHttpRequest.php");
$result_filename = 'result.txt';
$hot_topics = array(
'britney',
'gaga',
'carol'
);
$handle = @fopen($result_filename, 'a+');
if (!$handle) {
exit("Unable to open $result_filename");
}
foreach($hot_topics as $topic) {
if (is_hot($topic)) {
fwrite($handle, "$topic found\r\n");
}
}
fclose($handle);
exit("\ncomplete");
function is_hot($news) {
$url = "https://localhost/search.aspx?search=".$news;
$ajax = new XMLHttpRequest();
$ajax->setRequestHeader("Cookie", "Cookie: host");
$ajax->open("GET", $url, true);
$ajax->send(null);
if ($ajax->status == 200) {
$rHeader = $ajax->getResponseHeader("Set-Cookie");
if (substr_count($rHeader, "Present!") > 0) {
return true;
}
}
return false;
}
Upvotes: 0
Reputation: 7750
Something like this would be very close to your actual code, but might not be recomanded
for($i = 1 ; $i <= 4 ; $i++)
fwrite($handle, "${Content$i}\r\n");
It is using variable variables : http://php.net/manual/en/language.variables.variable.php
Not the best solution here : why don't you simply use an array ?
$content[1]= hot("britney") ? "britney found" : "";
$content[2]= hot("gaga") ? "gaga found" : "";
$content[3]= hot("carol") ? "carol found" : "";
for($i = 1 ; $i <= 4 ; $i++)
fwrite($handle, $Content[$i]."\r\n");
Or ever better, use the solution of captaintokyo , because you might not want empty lines in your text file.
Upvotes: 2