simplexml_load_file generates same post repeatedly from WP feed - php

I'm using simplexml_load_file to get rss feed from from a wordpress blog. Here is my code
$rssfile = simplexml_load_file( "http://blog.sufuraamathi.com/?feed=rss2" );
$items = $rssfile->channel->item ;
foreach( $items as $item ) {
$article = array();
$article['title'] = $item->title;
$article['link'] = $item->link;
$article['category'] = $item->category;
}
foreach( $items as $item ) { ?>
<?php if($article['category']=="Uncategorized") { ?>
<div><?php echo $article['title'];?></div>
<?php
} } ;
?>
The Problem: It outputs the same post repeatedly x times, where x is total number of posts. Right now there are only two posts in the Uncategorized category and three more posts in other categories. But the code echos the following:
<div>Hello world!</div>
<div>Hello world!</div>
<div>Hello world!</div>
<div>Hello world!</div>
<div>Hello world!</div>

Your problem is on the fifth row of your posted code. You must take out the array definition of the first foreach loop:
$rssfile = simplexml_load_file( "http://blog.sufuraamathi.com/?feed=rss2" );
$items = $rssfile->channel->item ;
$article = array(); // <- put it here
foreach( $items as $item ) {
$article['title'] = $item->title;
$article['link'] = $item->link;
$article['category'] = $item->category;
}
...
as your current solution resets the $article array for each row. But why don't you loop everything in one foreach loop? If you're not using $article for some other purpose I don't see the use of assigning $item data to an array. Code could be simplified:
$rssfile = simplexml_load_file( "http://blog.sufuraamathi.com/?feed=rss2" );
$items = $rssfile->channel->item ;
foreach( $items as $item ) { ?>
<?php if($item->category=="Uncategorized") { ?>
<div><?php echo $item->title;?></div>
<?php
} } ?>

Related

How to append count to variables in php

I am just starting to learn PHP and to compound the issue I am trying to modify existing code to match what I am attempting to do. I have multiple variables I am trying to define all while partially using a counter. My problem is appending the count to my individually defined variables. Also, I'm sure there is a cleaner way to do this (like a loop or nested array), I just can't see how.
<?php
$pageId0 = opt('first_tab_page');
$post0 = get_post($pageId0);
$content0 = apply_filters('the_content', $post0->post_content);
$icon0 = wp_get_attachment_image_src( get_post_thumbnail_id( $post0->ID ), 'full' );
$pageId1 = opt('second_tab_page');
$post1 = get_post($pageId1);
$content1 = apply_filters('the_content', $post1->post_content);
$icon1 = wp_get_attachment_image_src( get_post_thumbnail_id( $post1->ID ), 'full' );
$pageId2 = opt('third_tab_page');
$post2 = get_post($pageId2);
$content2 = apply_filters('the_content', $post2->post_content);
$icon2 = wp_get_attachment_image_src( get_post_thumbnail_id( $post2->ID ), 'full' );
?>
<div>
<?php echo $icon0[0]; ?>
</div>
<div>
<?php echo $icon1[0]; ?>
</div>
<div>
<?php echo $icon2[0]; ?>
</div>
<?php
$tab_position = opt('tab_position');
if ($tab_position == '' || count($tab_position) != 3) {
$tab_position = array(0, 1, 2);
}
for($i=0; $i < count($tab_position); $i++)
{
$selected = '';
if (opt('default_selected_tab') == $tab_position[$i]){
$selected = 'class="selected"';
}
?>
<a <?php echo $selected; ?> href="#tab<?php echo $tab_position[$i];?>">
<?php echo $content//should be 0 to start; ?>
</a>
<?php } ?>
Here is a short example on using arrays. comment in code
// Storing tab names to an array, just add more tabs if required
// and details for all those will be loaded in the following arrays
$tabs = array('first_tab_page', 'second_tab_page', 'third_tab_page');
//declare arrays to store (not required, but better practice)
$pageids = array();
$posts = array();
$content = array();
$icons = array();
//Iterate through the tabs array
foreach ($tabs as $tab){
//Store page id and post in a variable, we require it
$pageid = opt($tab);
$post = get_post($pageid);
// Store pageid in pageids. note the [] this means it will store pageid at next index
//also store other items
$pageids[] = $pageid;
$posts[] = $post;
$contents[] = apply_filters('the_content', $post->post_content);
$icons[] = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );
}
now $icons[0] will contain first icon $icons[1] the second one and so on. Same thing applies to other variables.
Note: this code is just typed in here and not checked. Please fix if there is any syntax errors. Also note this is one way and there are more ways.
But I would suggest keeping data of each page together.
Edit: Here is how you can keep things together (only relevant parts shown)
$tabs = array('first_tab_page', 'second_tab_page', 'third_tab_page');
$pages = array();
foreach ($tabs as $tab){
$pageid = opt($tab);
$post = get_post($pageid);
$content = apply_filters('the_content', $post->post_content);
$icon = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );
//Store everything to $pages array
$pages[] = array('pageid' => $pageid, 'post' => $post, 'content' => $content, 'icon', $icon);
}
foreach ($pages as $page){
?>
<div>
<?php echo $page['icon'][0]; ?>
</div>
<?php } ?>
foreach ($pages as $page){
?>
<a <?php echo $selected; ?> href="#tab<?php echo $tab_position[$i];?>">
<?php echo $page['content']; //echo the content of page ?>
</a>
<?php } ?>
Instead of foreach to display you can use index also like
<a <?php echo $selected; ?> href="#tab<?php echo $tab_position[$i];?>">
<?php echo $pages[0]['content']; //echo the content of the first page ?>
</a>
<a <?php echo $selected; ?> href="#tab<?php echo $tab_position[$i];?>">
<?php echo $pages[1]['content']; //echo the content of the second page ?>
</a>
I guess there is no other way then (nested) arrays. Also I'm thinking that arrays are a acceptable solution.
foreach ($tabs as $tab) {
$tab['content'] = 'somecontent';
$tab['counter'] = 'counter';
}
or
foreach ($tabs as $tab) {
$tab = [
"content" => "content",
"counter" => "counter"];
}
I'm not sure what you are trying to do as your question is not very clear to me. But i think you are trying to echo $content in your last line of code. If yes, just put your all your variables $content1, $content2 and $content3 in an array like below:
$contents = array($content1, $content2, $content3);
Then use foreach loop and traverse this array like this.
$count = 0;
foreach($contents as $content) {
echo $content.$count;
$count++;
}
Try and let me know if it works for you.

RSS feed limit items

How can i limit the items from my RSS-feed? (Example: 5 items). I hope someone can help me with this code.
<?php
$url = "LINK TO RSS";
$rss = simplexml_load_file($url);
if($rss)
{
$items = $rss->channel->item;
foreach($items as $item)
{
$title = $item->title;
$link = $item->link;
$published_on = $item->pubDate;
$description = $item->description;
echo '<p class="rss-feed">'.$title.'</p>';
echo '<p>'.$description.'</p>';
}
}
?>
If you want to limit the number of items displayed you can use the array_slice function to store a subset of the retrieved values in $items, e.g. change:
$items = $rss->channel->item;
to:
$items = array_slice($rss->channel->item, 0, 5);
If you want to change the number of items fetched from the URL then you need to check whether/how this URL supports this behaviour.

Loop a foreach json loop in another foreach json loop

I'm at a 24 hour hackathon trying to solve this so, excuse if it's a little rushed.
1st for each loop works fine, I'm getting a list of categories from this url
https://dev.xola.com/api/categories
I grab the list with this
$fullurl = "https://dev.xola.com/api/categories";
$string .= file_get_contents($fullurl); // get json content
$json_a = json_decode($string, true); //json decoder
then loop it with this
<?
foreach($json_a as $v)
{?>
echo $v ?}>
Now with the second for each look, I want to grab the items from this url
https://dev.xola.com/api/experiences
that match the category from the last url
so samething
$fullurl = "https://dev.xola.com/api/categories";
$string .= file_get_contents($fullurl); // get json content
$json_b = json_decode($string, true); //json decoder
here's the complete loop I tried
<?
$i=0;
foreach($json_a as $v)
$i++
{?>
echo $v ?
foreach($json_b as $x){?>
if($v==$x):
echo $v
endif;
?>
}?>
This will create a $result array with only the data that had the categories early acquired:
<?php
$categories_url = "https://dev.xola.com/api/categories";
$data = file_get_contents($categories_url);
$categories = json_decode($data, true);
$experiences_url = "https://dev.xola.com/api/experiences";
$data = file_get_contents($experiences_url);
$experiences = json_decode($data, true);
$result = array();
foreach ($experiences['data'] as $experience)
{
if (in_array($experience['category'], $categories))
{
$result[] = $experience;
}
}
print_r($result);
And you can easily read the result with:
foreach ($result as $item)
{
echo $item['category'], "\n";
echo $item['desc'], "\n";
//... other data available ...
}
The data structure of the experiences JSON is not the same as the categories JSON, therefore if($v==$x) will never match. If you want to find all results in experiences with a category from the categories url you can do the following:
<?
$BASE_URL = 'https://dev.xola.com/api/';
$categories = json_decode(file_get_contents($BASE_URL . 'categories'));
$experiences = json_decode(file_get_contents($BASE_URL . 'experiences'));
$matches = array();
foreach( $categories as $category ) {
foreach( $experiences->data as $experience ) {
if( $experience->category === $category ) {
$matches[] = $experience;
}
}
}
?>
<? foreach( $matches as $match ) : ?>
<? echo $match->category; ?><br>
<? endforeach; ?>

magento tracking pixel checkout

I'm trying to integrate a tracking pixel into the magento success page. For testing I build the following code and implemented it into line > 45 in success.phtml file within the template folder. Actually the variables are all empty. What's wrong?
<?php
<?php
$lastOrderId = Mage::getSingleton('checkout/session')->getLastOrderId();
$order = Mage::getSingleton('sales/order');
$order->load($lastOrderId);
$skus = array();
$qtys = array();
$amounts = array();
foreach ($order->getAllItems() as $item){
$skus[$item->getProductId()] = $item->getSku();
$names[$item->getProductId()] = $item->getName();
$qtys[$item->getProductId()] = $item->getQtyOrdered() * 1;
$amounts[$item->getProductId()] = $item->getRowTotal() * 100;//or $item->getPrice()*$item->getQtyOrdered();//but this will ignore any applied coupons
}
$skuspipe = implode("|", $skus);
$namespipe = implode("|", $names);
$qtyspipe = implode("|", $qtys);
$amountspipe = implode("|", $amounts);
<!--
OrderID: <?php echo $orderID; ?>
skus: <?php print_r($skus); ?>
names: <?php print_r($names); ?>
qtys: <?php print_r($qtys); ?>
amounts: <?php print_r($amounts); ?>
skupipe: <?php echo $skupipe; ?>
namespipe: <?php echo $namespipe; ?>
qtyspipe: <?php echo $qtyspipe; ?>
amountspipe: <?php echo $amountspipe; ?>
-->
Thank you!
In Collections, Magento often only loads kind of a stub of data for each item.
You could load the whole objects by using
$item->load( $item->getId() );
on each iteration.
Also, try to debug output the collection first to see if there are any items found.

PHP + RSS duplicate elements

Im using this PHP to get a list of Title's from an RSS feed:
<?php require_once('magpie/rss_fetch.inc');
$rss = fetch_rss('http://live.visitmix.com/Sessions/RSS');
foreach ($rss->items as $item) {
$cat = $item['category'];
$title = $item['title'];
echo '<li class="'.$cat.'">'.$title.'</li>';
}
?>
I want to use <category> and add it as the class, however the <category> element appears for each <item> 1,2,3,4 or more times depending on the Title. How can I take the category element and seperate each category with a space if there is more than 1?
what about accumulating the categories in an array and then implode the array?
$categoriesArray = array();
foreach ($rss->items as $item) {
array_push($categoriesArray, $item['category']);
}
$categories = implode(" ", $categoriesArray);
EDIT TO ADD
If the categories are cumulated, you can try something like this:
$categoriesByTitle = array();
foreach ($rss->items as $item) {
$currentTitle = $item['title'];
$categories = $categoriesByTitle[$currentTitle];
if ($categories == NULL) {
$categories = array();
$categoriesByTitle[$currentTitle] = $categories;
}
if (!in_array($item['category'], $categories)) {
array_push($categories, $item['category']);
}
}
foreach ($categoriesByTitle as $title=>$category) {
// use implode for each title
$categoryString = implode(" ", $category);
echo '<li class="'.$categoryString.'">'.$title.'</li>';
}
Check this reference for arrays, it could be very useful for dealing with this kind of problems

Categories