If Its empty, return something in PHP - php

i have a code, it's getting data but when it gets nothing i want it to return something.
$upcoming = simplexml_load_file('http://api.website.com');
foreach($upcoming->trailer as $x => $updates) {
$content.= '<center><br><span> ' . $updates->embed . '</span></center>';
}
This is the code. It's getting data but when it got nothing, i would like it to say NO Videos.
How can i do that? I tried strlen() but i couldn't applied it.
I tried strpos but it didn't work either.

You can simply check the result of simplexml_load_file and act accordingly
if (false === $upcoming) {
echo "No Videos";
} else {
//your foreach loop here
}

$upcoming = simplexml_load_file('http://api.website.com');
if($upcoming == null || $upcoming == false){
$content = "No videos";
}
else{
foreach($upcoming->trailer as $x => $updates) {
$content.= '<center><br><span> ' . $updates->embed . '</span></center>';
}
}

Add some flag in your foreach to put a flag if anything has been printed or just check the $upcoming.
Then just check the flag and echo "no videos" your message.
Do it like this:
$Something=false;
$upcoming = simplexml_load_file('http://api.website.com');
foreach($upcoming->trailer as $x => $updates) {
if($updates->embed){
$Something=true;
}
$content.= '<center><br><span> ' . $updates->embed . '</span></center>';
}
if(!$Something){
echo "<center>No videos</center>";
}
Or:
$upcoming = simplexml_load_file('http://api.website.com');
if(!$upcoming){
echo "<center>No videos</center>";
}
else{
foreach($upcoming->trailer as $x => $updates) {
if($updates->embed){
$Soemthing=true;
}
$content.= '<center><br><span> ' . $updates->embed . '</span></center>';
}
}

Related

Problem reading RSS feed programmatically using PHP

I have a newsfeed link from an Indian newspaper as follows:
https://www.hindustantimes.com/rss/cities/delhi/rssfeed.xml
I am trying to extract some information from it using PHP and simpleXML
$feedURL="https://www.hindustantimes.com/rss/cities/delhi/rssfeed.xml";
$array = get_headers($feedURL);
$statusCode = $array[0];
echo('<br>'.$statusCode.'<br>');
if (strpos($statusCode, "404")==FALSE) {
echo('Reading ' . $feedURL . '<br>');
$out = htmlspecialchars(file_get_contents($feedURL), ENT_QUOTES);
echo($out);
if (stripos($out, "<feed ") != FALSE) {
$feedType = 'ATOM';
$countATOM += 1;
} else if (stripos($out, "<rss") != FALSE) {
$feedType = 'RSS';
$countRSS += 1;
} else {
$feedType = 'UNREADABLE';
$countUNREADABLE += 1;
}
echo('<br>' . $feedType . '<br>');
echo('<br>-------------------------------------------------------------------------<br>');
if ($feedType == 'ATOM') {
$xmlOut = simplexml_load_string(file_get_contents($feedURL));
echo($xmlOut.'<br>-------------------------------------------------------------------------<br>');
if ($xmlOut === false) {
echo("Failed loading XML: ");
foreach (libxml_get_errors() as $error) {
echo ("<br>" . $error->message);
}
} else {
foreach ($xmlOut->entry as $entry) {
if (isset($xmlOut->entry->title) && isset($xmlOut->entry->link) && isset($xmlOut->entry->updated) && isset($xmlOut->entry->summary)){
$title=$xmlOut->entry->title;
$link=$title=$xmlOut->entry->link['href'];
$updated=$xmlOut->entry->updated;
$summary=$xmlOut->entry->summary;
if(isImportantNews($title) || isImportantNews($summary)){
$insertNewsCmd=$insertNewsCmd
."('".$link."',"
."'".stripSpecialChars($title)."',"
."'".setDate($updated)."'),";
}
}
echo($entry->updated . "<br>");
}
}
} elseif ($feedType == 'RSS') {
$xmlOut = simplexml_load_string(file_get_contents($feedURL));
print_r($xmlOut);
echo('<br>-------------------------------------------------------------------------<br>');
if ($xmlOut === false) {
echo("Failed loading XML: ");
foreach (libxml_get_errors() as $error) {
echo ("<br>" . $error->message);
}
} else {
foreach ($xmlOut->channel->item as $item) {
if (isset($item->title) && isset($item->link) && isset($item->description) && isset($item->pubDate)) {
$title = $item->title;
$link = $item->link;
$descr = $item->description;
$pubDate = $item->pubDate;
echo($title.'<br>'.$link.'<br>'.$descr.'<br>');
echo('<br>-------------------------------------------------------------------------<br>');
if(isImportantNews($title) || isImportantNews($descr)){
$insertNewsCmd=$insertNewsCmd
."('".$link."',"
."'".stripSpecialChars($title)."',"
."'".setDate($pubDate)."'),";
}
echo($entries->pubDate. "<br>");
}
}
}
} else {
continue;
}
break;
} else {
echo($feedURL . ' encountered problems being read...' . '<br>');
}
Basically what I am doing in the program is that I am using the above link (after determining if it is ATOM or RSS) to extract the news summary and description and determine if it is important news using the isImportantNews() method. If so, I store it in a database.
My problem is that if I open the above link in a browser directly, I can get to see the information without any issues but trying to read it using the above code returns a HTTP 403 Forbidden status code
Why is this happening and is there a way to get around this issue? Being able to open it directly tells me that the 403 maybe coming up due to programatic access attempt (?) But I am not certain about it. I also tried the following ways to read it with the same expected failure
echo('read file ####################################################################################################');
echo readfile("https://www.hindustantimes.com/rss/cities/delhi/rssfeed.xml"); //needs "Allow_url_include" enabled
echo('<br>include ####################################################################################################');
echo include("https://www.hindustantimes.com/rss/cities/delhi/rssfeed.xml"); //needs "Allow_url_include" enabled
echo('<br>file get contents ####################################################################################################');
echo file_get_contents("https://www.hindustantimes.com/rss/cities/delhi/rssfeed.xml");
echo('<br>stream get contents####################################################################################################');
echo stream_get_contents(fopen('https://www.hindustantimes.com/rss/cities/delhi/rssfeed.xml', "r")); //you may use "r" instead of "rb" //needs "Allow_url_fopen" enabled
echo('<br>get remote data ####################################################################################################');
echo get_remote_data('https://www.hindustantimes.com/rss/cities/delhi/rssfeed.xml');
$feedURL = "https://www.hindustantimes.com/rss/cities/delhi/rssfeed.xml";
$out = htmlspecialchars(file_get_contents($feedURL), ENT_QUOTES);
echo($out);
Any help or insight would be most appreciated.

Php flip the echo result

I confused the method to flip the place of the echo result, below is my code
while ($looptools == 0) {
$mysqlihelper = " SELECT * FROM soal WHERE nomorsoal = $numberofmysqli ";
$mysqliquery = mysqli_query($konek, $mysqlihelper);
$resultquery = mysqli_fetch_assoc($mysqliquery);
$resulttextjudul = $resultquery['judul'];
if ($resulttextjudul == null) {
unset($resulttextjudul);
$resulttextjudul = "Tunggu Soal Berikutnya ! ..";
$nullerror = true;
} else {
}
if ($nullerror == true) {
echo "<div class=\"head-main-recenttest-result\" style=\"text-decoration:none\">" . $resulttextjudul . "</div>";
} else {
echo "<div class=\"head-main-recenttest-result\" style=\"text-decoration:none\">" . $resulttextjudul . "</div>";
}
if ($nullerror == true) {
mysqli_close($konek);
break;
} elseif ($looptools == 10) {
mysqli_close($konek);
break;
} else {
}
}
As you see in the "while", it's echo the first result and the second result below it, but I want the first result in below of the second result, can anyone tell me the method to do it?
I assume you mean you want to print all successes followed by all errors, or something like that. Here's how:
if($nullerror == true){
$errors .= "<div class=\"head-main-recenttest-result\" style=\"text-decoration:none\">".$resulttextjudul."</div>";
}else{
$successes .= "<div class=\"head-main-recenttest-result\" style=\"text-decoration:none\">".$resulttextjudul."</div>";
}
Then, when the while loop is done:
echo $successes ;
echo $errors ;
If you really want to work your way backwards through the results in $mysqliquery, that's a different answer.
UPDATE: to reverse the order of successes / errors on display, just put the latest additions in front:
if($nullerror == true){
$errors = "<div class=\"head-main-recenttest-result\" style=\"text-decoration:none\">".$resulttextjudul."</div>" . $errors;
}else{
$successes = "<div class=\"head-main-recenttest-result\" style=\"text-decoration:none\">".$resulttextjudul."</div>" . $successes ;
}
sorry if i answer my own question because i found it out myself
use mysqli_num_rows or often called mysqli count
http://php.net/manual/en/mysqli-result.num-rows.php

Return true or false with preg match instead of echoing out a sentence

I am using the following to check to see if the data from a form contains certain words, the problem is though, when it checks I get "a match was found" or "a match was not found" over and over again a million times. How can I just assign a true or false value for the whole sentence that is posted ?. I want to then add something like....if true dump this post, if false process it and put it in the database.
<?php
$message = $_POST['message'];
echo $message;
$targets = array('viagra', 'prescription', 'drugs', 'zyban', 'zithromax', 'voltaren', 'cilias', 'FDA');
foreach($targets as $t)
{
if (preg_match("/\b" . $t . "\b/i", $message)) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
}
?>
function containsSpam($message) {
$targets = array('viagra', 'prescription', 'drugs', 'zyban', 'zithromax', 'voltaren', 'cilias', 'FDA');
foreach($targets as $t)
{
if (preg_match("/\b" . $t . "\b/i", $message)) {
//A match was found.
return true;
}
}
return false;
}
If i get it right you need to set a stop value like this
<?php
function containsSpam($message) {
$targets = array('viagra', 'prescription', 'drugs', 'zyban', 'zithromax', 'voltaren', 'cilias', 'FDA');
$stop = false;
foreach($targets as $t)
{
if (preg_match("/\b" . $t . "\b/i", $message)) {
//A match was found.
$stop = true;
break;
}
}
//And you can then do something like this
if ($check) {
//Insert it
} else {
//Dump it
}
}
?>

php foreach results

foreach ($flr_array as $flr) {
if (!($flr = trim($flr)))
continue;
//list($flr, $keyword) = explode('|', $flr, 2);
$ip = '';
$err_msg = isValidFLR($flr, $ip);
if (!$err_msg) {
list($randlink, $lastid, $scr) = addLink($flr, $ip);
$flr = stripslashes($flr);
$url_array[$i]['number'] = $i + 1;
$url_array[$i]['flr'] = $flr;
$url_array[$i]['flr_substr'] = (strlen($flr) > 33) ? substr($flr, 0, 33) . '...' : $flr;
$url_array[$i]['randlink'] = $randlink;
$url_array[$i]['fullrand'] = $config['indexurl'] . $config['mod_rewrite_char'] . $randlink;
$url_array[$i]['scr'] = $scr;
$url_array[$i]['id'] = $lastid;
$url_array[$i]['flr_length'] = strlen($flr);
$url_array[$i++]['randlink_length'] = strlen($config['indexurl'] . $config['mod_rewrite_char'] . $randlink);
////
//$smarty->assign("flr_length", strlen($_REQUEST['flr']));
//$smarty->assign("randlink_length", strlen($config['indexurl'] . $config['mod_rewrite_char'] . $randlink));
////
} else {
js_alert($err_msg);
}
}
In function isValidFLR these is part of captcha check:
if ($config['captcha_check']) {
if (verifyCaptcha() == false) {
return 'Wrong code!';
}
}
Let's say in textarea i enter:
google.com
google.de
google.net
and enter wrong captcha code, so it gives me 3 messages of Wrong code!
It's happen i think because of foreach. Any ideas how to make in foreach display only one error message ?
Your question is hard to understand but I think you are right (in the foreach)....
if err_msg <> '' then you should put a break in your code to get out of the foreach (if that is what you want).
else {
js_alert($err_msg);
break; //this will break out of for loop
//or return false if it a function
}

php regex failed, why?

The value is AbcDefg_123.
Here is the regex:
function checkAlphNum($alphanumeric) {
$return = false;
if((preg_match('/^[\w. \/:_-]+$/', $alphanumeric))) {
$return = true;
}
return $return;
}
Should allow a-zA-Z0-9.:_-/ and space in any order or format and does need all but at least one character.
EDIT: Sorry again, looks like var_dump() is my new best friend. I'm working with XML and it's passing the tag as well as the value.
#SilentGhost thnx for the tips.
It works for me too.
<?php
class RegexValidator
{
public function IsAlphaNumeric($alphanumeric)
{
return preg_match('/^[\w. \/:_-]+$/', $alphanumeric);
}
}
?>
and this is how I am testing it.
<?php
require_once('Classes/Utility.php');
$regexVal = new RegexValidator();
$list = array("abcd", "009aaa", "%%%%", "0000(", "aaaa7775aaa", "$$$$0099aaa", "kkdkdk", "aaaaa", "..0000", " ");
foreach($list as $value)
{
if($regexVal->IsAlphaNumeric($value))
{
echo $value . " ------>passed";
echo "<BR>";
}
else
{
echo $value . "------>failed";
echo "<br>";
}
}
?>
function checkAlphNum($alphanumeric) {
$return = false;
if((preg_match('/^[A-Za-z0-9\w. \/:_-]+$/', $alphanumeric))) {
$return = true;
}
return $return;
}
print checkAlphNum("AbcDefg_123");
Returns true.

Categories