Fetch rss with php - Conditional for Enclosured image and not Enclosured - php

I'm working on a project and it's something new for me. I'll need to fetch rss content from websites, and display Descripion, Title and Images (Thumbnails). Right now i've noticed that some feeds show thumbnails as Enclosure tag and some others dont. right now i have the code for both, but i need to understand how i can create a conditional like:
If the rss returns enclosure image { Do something }
Else { get the common thumb }
Here follow the code that grab the images:
ENCLOSURE TAG IMAGE:
if ($enclosure = $block->get_enclosure())
{
echo "<img src=\"" . $enclosure->get_link() . "\">";
}
NOT ENCLOSURE:
if ($enclosure = $block->get_enclosure())
{
echo '<img src="'.$enclosure->get_thumbnail().'" title="'.$block->get_title().'" width="200" height="200">';
}
=================================================================================================
PS: If we look at both codes they're almost the same, the difference are get_thumbnail and get_link.
Is there a way i can create a conditional to use the correct code and always shows the thumbnail?
Thanks everyone in advance!
EDITED
Here is the full code i have right now:
include_once(ABSPATH . WPINC . '/feed.php');
if(function_exists('fetch_feed')) {
$feed = fetch_feed('http://feeds.bbci.co.uk/news/world/africa/rss.xml'); // this is the external website's RSS feed URL
if (!is_wp_error($feed)) : $feed->init();
$feed->set_output_encoding('UTF-8'); // this is the encoding parameter, and can be left unchanged in almost every case
$feed->handle_content_type(); // this double-checks the encoding type
$feed->set_cache_duration(21600); // 21,600 seconds is six hours
$feed->handle_content_type();
$limit = $feed->get_item_quantity(18); // fetches the 18 most recent RSS feed stories
$items = $feed->get_items(0, $limit); // this sets the limit and array for parsing the feed
endif;
}
$blocks = array_slice($items, 0, 3); // Items zero through six will be displayed here
foreach ($blocks as $block) {
//echo $block->get_date("m d Y");
echo '<div class="single">';
if ($enclosure = $block->get_enclosure())
{
echo '<img class="image_post" src="'.$enclosure->get_link().'" title="'.$block->get_title().'" width="150" height="100">';
}
echo '<div class="description">';
echo '<h3>'. $block->get_title() .'</h3>';
echo '<p>'.$block->get_description().'</p>';
echo '</div>';
echo '<div class="clear"></div>';
echo '</div>';
}
And here are the XML pieces with 2 different tags for images:
Using Thumbnails: view-source:http://feeds.bbci.co.uk/news/world/africa/rss.xml
Using Enclosure: http://feeds.news24.com/articles/news24/SouthAfrica/rss

Is there a way i can create a conditional to use the correct code and always shows the thumbnail?
Sure there is. You've not said in your question what blocks you so I have to assume the reason, but I can imagine multiple.
Is the reason a decisions with more than two alternations?
You handle the scenario of a feed item having no image or an image already:
if ($enclosure = $block->get_enclosure())
{
echo '<img class="image_post" src="'.$enclosure->get_link().'" title="'.$block->get_title().'" width="150" height="100">';
}
With your current scenario there is only one additional alternation which makes it three: if the enclosure is a thumbnail and not a link:
No image (no enclosure)
Image from link (enclosure with link)
Image from thumbnail (enclosure with thumbnail)
And you then don't know how to create a decision of that. This is what basically else-if is for:
if (!$enclosure = $block->get_enclosure())
{
echo "no enclosure: ", "-/-", "\n";
} elseif ($enclosure->get_link()) {
echo "enclosure link: ", $enclosure->get_link(), "\n";
} elseif ($enclosure->get_thumbnail()) {
echo "enclosure thumbnail: ", $enclosure->get_thumbnail(), "\n";
}
This is basically then doing the output based on that. However if you assign the image URL to a variable, you can decide on the output later on:
$image = NULL;
if (!$enclosure = $block->get_enclosure())
{
// nothing to do
} elseif ($enclosure->get_link()) {
$image = $enclosure->get_link();
} elseif ($enclosure->get_thumbnail()) {
$image = $enclosure->get_thumbnail();
}
if (isset($image)) {
// display image
}
And if you then move this more or less complex decision into a function of it's own, it will become even better to read:
$image = feed_item_get_image($block);
if (isset($image)) {
// display image
}
This works quite well until the decision becomes even more complex, but this would go out of scope for an answer on Stackoverflow.

Related

Images are displaying vertically rather horizontally

Update: After looking at my HTML code in browser I figure out I need to only run the SQL code inside php just once in foreach loop and the images will be displayed horizontally. I was wondering how do I make that sql code run only once in that loop?
When I write the below code inside foreach ($ffs as $ff) {
Code:
echo "<h4 class='text-right'>{$Data[$increaseForText]["username_for_info"]}</h4>";
echo "<h2>{$Data[$increaseForText]["_name"]}</h2>";
echo "<p>{$Data[$increaseForText]["_desc"]}<p>";
So when this code is inside that foreach loop the images displays in vertical and I want my images to be displayed in horizontal (one next to other). But, if I remove that code from foreach and put it outside foreach code the image are displayed horizontally and works fine. I have tried CSS to display the image horizontally, but it only works if I remove that code from foreach. For some reason the above code (In foreach) somehow forcing the images to display in vertical, so no matter what I do it displays in vertical (the images).
I can't put my code outside foreach. I know I can use foreach to loop through my SQL code and it works fine, but the thing is I want it to work like first load images then first row only from sql, then 2nd image and 2nd row from sql and for that to make it work the only way is to put inside foreach my sql code, so it loads one at a time or else if I put it outside foreach It will load all the data of sql at once (1 row to 9 let's say) then all the images which makes no sense. I am storing my images in my hosting website files.
My question is how do I force my images to display horizontally one next to other?
My code:
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', '1');
require "navigationbar.php";
require "testing.php";
?>
<html>
<head>
<link rel="stylesheet" href="userprofilestyl.css">
</head>
<body>
<hr>
<?php
global $username;
//username to get data of specific user
$username = $_SESSION['name'];
//to get image by username
$image = "images/$username";
global $increaseForText;
$increaseForText = 0;
function listFolderFiles($dir, $username, $increaseForText)
{
//getting images
$ffs = scandir($dir);
unset($ffs[array_search('.', $ffs, true)]);
unset($ffs[array_search('..', $ffs, true)]);
// prevent empty ordered elements
if (count($ffs) < 1) {
return;
}
$column_count = 0;
$sql = "select username_for_info, _name, _desc
from info_desc where username_for_info = '$username'";
try {
require "testing.php";
$stmt = $conn->prepare($sql);
$stmt->execute();
$Data = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo '<div class="image-container">';
foreach ($ffs as $ff) {
//select data from database
$s = "'<li>'.$ff";
$saving = "$dir/$ff";
$string = "$saving";
global $string_arr;
$string_arr = (explode("/", $string));
$sav;
$sav = '<li>' . $ff;
global $sa;
$sa = "$ff";
if (is_dir($dir . '/' . $ff)) {
listFolderFiles($dir . '/' . $ff, $username, $increaseForText);
}
//printing image
if (is_file($saving)) {
echo '<img src="' . $saving . ' " width="100" height="100" alt="Random image" />';
}
//printing text
echo "<h4 class='text-right'>{$Data[$increaseForText]["username_for_info"]}</h4>";
echo "<h2>{$Data[$increaseForText]["_name"]}</h2>";
echo "<p>{$Data[$increaseForText]["_desc"]}<p>";
$increaseForText++;
}
} catch (PDOException $e) {
echo '{error":{"text":' . $e->getMessage() . '}}';
}
echo '</div>';
}
listFolderFiles($image, $username, $increaseForText);
?>
</body>
</html>
Add this to your css file:
.image-container{
display:inline-flex;
flex-flow:row;
}
This will change the flow of every element inside the div with the class "image-container" from vertically to horizontally
Foreach has nothing to do with making the images display vertically, there should be something wrong with the HTML or CSS. Make sure your tags are closed, such as your p and li tags.
There are alot of ways to make the images display horizontally, it would easier if you can send a jsfiddle or a code snippet.
But try this on .image-container:
display: flex !important;
flex-flow: row;

php barcode - display multiple barcode in single page

I created a php page that print the barcode. Just to view it before i print it on an A4. Still in testing phase. The codes are as below.
<?php
include('include/conn.php');
include('include/Barcode39.php');
$sql="select * from barcode where b_status = 'NOT-PRINTED'";
$result=mysqli_query($conn,$sql);
echo mysqli_num_rows($result);
$i=0;
while($row=mysqli_fetch_assoc($result)){
$acc_no = $row["b_acc_no_code"];
$bc = new Barcode39($row["b_acc_no_code"]);
echo $bc->draw();
$bc->draw($acc_no.$i.".jpg");
echo '<br /><br />';
$i++;
}
?>
Without the while loop, it can be printed, but only one barcode. How to make it generate, for example in the database have 5 values, it will print 5 barcode in the same page. Thanks in advance
Try to use another bar code source. Because It is generate only one bar code per page. Can't able to create multiple bar code per page.
I know this is an older post but comes up in searches so is probably worth replying to.
I have successfully used the Barcode39 to display multiple barcodes. The trick is to get base64 data from the class and then display the barcodes in separate HTML tags.
The quickest way to do this is to add a $base64 parameter to the draw() method:
public function draw($filename = null, $base64 = false) {
Then, near the end of the draw() method, modify to buffer the imagegif() call and return the output in base64:
// check if writing image
if ($filename) {
imagegif($img, $filename);
}
// NEW: Return base 64 for the barcode image
else if ($base64) {
ob_start();
imagegif($img);
$image_data = ob_get_clean();
imagedestroy($img);
return base64_encode($image_data);
}
// display image
else {
header("Content-type: image/gif");
imagegif($img);
}
Finally, to display multiples from the calling procedure, construct the image HTML in the loop and display:
// assuming everything else has been set up, end with this...
$base64 = $barcode->draw('', true); // Note the second param is set for base64
$html = '';
for ($i = 0; $i < $numBarcodes; $i++) {
$html .= '<img src="data:image/gif;base64,'.$base64.'">';
}
die('<html><body>' . $html . '</body></html>');
I hope this helps anyone else facing this challenge.

Php image show issue

I'm confused! Basically i've a form with 3 field ex: subject, image, message. So,
(1) If i upload image it's should be show image,
(2) if i don't upload image it's should be show just only subject and message no image box and
(3) if i don't upload image and if there are a youtube link in message box then it's should be show the vedio. **
Following is my php code, but i can't solved the number 3 point! **
<?php
if(empty($imgname))
{
echo '';
}
elseif(!empty($imgname))
{
echo "<span class='vedio'>";
echo '<img src="' . $upload_path . '/' . $imgname . '" width="195" height="130"
style=" background-color:f2f4f6;" />';
echo "</span>";
}
else
{
echo "<span class='vedio'>";
require_once("func.php");
if (preg_match('%(?:youtube\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)
([^"&?/ ]{11})%i', $msg, $match))
{
// echo $video_id = $match[1];
}
echo #get_youtube_embed($video_id = $match[1]);
echo "</span>";
}
?>
Any Idea or Solution that would be better for me.
Shibbir.
You'll never get into your else statement because of your preceding if conditions. In ALL cases, $imgname will either be empty, or not empty.
To demonstrate further:
if (empty($imgname)) {
// ... First condition
} else if (!empty($imgname)) {
// ... Last possible condition
} else {
// Will never reach here because $imgname will
// fall into one of the two of the above conditionals.
}
It's difficult to add to your code without full context, but it seems you may want to include the following after the above code (not with):
if(!empty($msg) && preg_match('%(?:youtube\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)
([^"&?/ ]{11})%i', $msg, $match)) {
require_once("func.php");
echo "<span class='vedio'>";
echo #get_youtube_embed($match[1]);
echo "</span>";
}

I need assistance with my wordpress theme

<?php
$i = 0;
$page = get_the_content();
$doc=new DOMDocument();
$doc->loadHTML($page);
$xml=simplexml_import_dom($doc);
$images=$xml->xpath('//img');
foreach ($images as $img) {
list($width, $height, $type, $attr) = getimagesize($img['src']);
if ($height > 149 ) {
echo '<img src="' . $img['src'] . '" alt=" ' . $img['alt'] . ' - funny and hot pictures" title=" ' . $img['title'] . ' - funny fail picture dump" onerror=\'this.style.display="none" \'><br>';
$i++;
if ($i == 3 ) { break;}
}
else
{
// don't display
}
}
?>
I replaced the "<?php the_content(); ?>" piece of code with the one above. It's supposed to strip out all of the text in my post and just leave the images which it does nicely. But when I embed a video the php breaks. How would I allow posts to show youtube videos?
You should look into using custom fields:
http://codex.wordpress.org/Custom_Fields
There is a great plugin that creates good admin control panels for them too:
http://wordpress.org/extend/plugins/advanced-custom-fields/
You could use a custom field to specifically put a video into the page.
Is there a particular reason you want to strip the text out of the post? - e.g. could you just not put text in the post at all? - or could the text be put into the excerpt instead, or into a custom field so that you don't have to over complicate the output code?

Hide Div if no image in the loop

Im looking to create a condition in wordpress loop. if no image then image box (.thumbHome{display:none})
this is in my function.php
function getThumbImages($postId) {
$iPostID = get_the_ID();
$arrImages =& get_children('post_type=attachment&post_mime_type=image&post_parent=' . $iPostID );
if($arrImages) {
$arrKeys = array_keys($arrImages);
$iNum = $arrKeys[0];
$sThumbUrl = wp_get_attachment_thumb_url($iNum, $something);
$sImgString = '<img src="' . $sThumbUrl . '" alt="thumb Image" title="thumb Image" />';
echo $sImgString;}
else {
echo '<script language="javascript">noImage()</script>';
}
}
And my javascript:
window.onload = noImage();
function noImage(){
document.getElementByClassName('.thumbHome').css.display = 'none';
}
I tried:
window.onload = noImage();
function noImage(){
$('.thumbHome').addClass('hide');
}
RESULT: class hide added to all loop
I cant figure it another way, since im still new in coding.
thx
Well first of all, you don't want to call these functions on window.onload. That's going to immediately set all class instances of .thumbHome to hidden without any conditions.
Here's a very easy way to fix this issue. There are probably more intricate ways, but this works well.
In your main loop, add an unique id to each .thumbHome div based on the image id. So like:
echo '<div class="thumbHome" id="thumb-' . $iNum . '"> ... </div>';
// or you could you use the post ID, doesn't matter, as long as you are consistent
Then your else conditional (for whether there's a thumbnail) could be changed to:
else {
echo '<script type="text/javascript">noImage("#thumb-' . $iNum . '")</script>';
}
and your js function could be:
function noImage(var){
$(var).hide();
}
This is not necessary the best way to do this, it's just the best way with the situtation you find yourself in now.

Categories