OK, so, I'm creating a page for a friend's podcast site that lists out all of the episodes to his podcast(s). Essentially, all I'm looking for is how to read the RSS Feed. Parse out the Nodes, and display the information on the screen. (eventually, I'm going to create a player that will play the episodes, but that's much later)
This is how I'm reading the RSS Feed (which is to one of my shows - for testing purposes).
click to see My Feed
<?php
//Errors:
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$rss = new DOMDocument();
$rss->load('http://tbpc.podbean.com/feed/');
$feed = array();
foreach ($rss->getElementsByTagName('item') as $node) {
$item = array (
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
'guid' => $node->getElementsByTagName('guid')->item(0)->nodeValue,
'enclosure' => $node->getElementsByTagName('enclosure')->item(0)->nodeValue,
);
array_push($feed, $item);
}
$limit = 1;
for($x=0;$x<$limit;$x++) {
$title = str_replace(' & ', ' & ', $feed[$x]['title']);
$link = $feed[$x]['link'];
$description = $feed[$x]['desc'];
$short = substr($description, 0, strpos( $description, '<'));
$file = $feed[$x]['guid'];
echo '<p><strong>'.$title.'</strong></p>';
echo '<p>'.$description.'</p>';
echo '<p>'.$short.'</p>';
echo '<p>'.$file.'</p>';
}
?>
The problem is - is that I have no idea how to get the information out of the attribute url of the enclosure node so I can display it on the page with the rest of the information (this will come in handy when I make the player - eventually).
SO! How do I get the url attribute from the enclosure node? Am I going about this all wrong?
Any helpful hints would be appreciated. Thanks.
Apologies if you're determined to use DOMDocument() in this, but since nobody has posted an answer so far...here's a script which uses simple_xml_load_file(), which I found quite easy to get to grips with.
<?php
$rss_array = array('http://rss.computerworld.com/computerworld/s/feed/topic/231', 'http://rss.computerworld.com/computerworld/s/feed/topic/230', 'http://rss.computerworld.com/computerworld/s/feed/topic/66', 'http://www.engadget.com/rss.xml', 'http://feeds.webservice.techradar.com/rss/new', 'http://feeds.arstechnica.com/arstechnica/index', 'http://www.notebookcheck.net/News.152.100.html', 'http://electronista.feedsportal.com/c/34342/f/626172/index.rss', 'http://www.anandtech.com/rss/pipeline/', 'http://www.digitimes.com/rss/daily.xml', 'http://feeds.feedburner.com/TechCrunch/', 'http://feeds2.feedburner.com/ziffdavis/pcmag/breakingnews', 'http://feeds.feedburner.com/Liliputing', 'http://feeds.slashgear.com/slashgear', 'http://feeds.feedburner.com/GizmagEmergingTechnologyMagazine', 'http://www.zdnet.com/news/rss.xml', 'http://feeds.feedburner.com/mobilityupdate', 'http://www.techmeme.com/feed.xml', 'http://www.notebookreview.com/rss.xml');
for ($i=0; $i<count($rss_array); $i++ ) {
$rssfeed = simplexml_load_file($rss_array[$i]);
foreach ($rssfeed->channel as $channel) {
echo '<h1>' . htmlentities($channel->title) . '</h1>';
echo '<p>' . htmlentities($channel->description) . '</p>';
echo '<p><a href="' . htmlentities($channel->link) . '">' .
htmlentities($channel->link) . '</a></p>';
echo '<input type="button" value=" >>> " onClick="downloadFileViaAjax(\'' . htmlentities($channel->link) . '\')">';
echo '<ul>';
foreach ($channel->item as $item) {
echo '<li><a href="' . htmlentities($item->link) . '">';
echo htmlentities($item->title) . '</a>';
// echo htmlentities($item->description) . '</li>';
echo '<input type="button" value=" >>> " onClick="downloadFileViaAjax(\'' . htmlentities($item->link) . '\')"></li>';
}
echo '</ul>';
}
}//fur ( $rss_array++ )
?>
Nodes have an getAttribute() method. So you can use:
$node->getElementsByTagName('enclosure')->item(0)->getAttribute('url')
But here is another and more comfortable way to fetch nodes and values from an XML DOM: Use Xpath. See this answer: https://stackoverflow.com/a/20225186/2265374
The $node->getElementsByTagName('enclosure')->item(0) will result in an error if no element is found (same goes for SimpleXML btw). If the node list is cast to string in Xpath, the result is just an empty string and no error is triggered.
You can directly fetch attributes this way, too. Like the url attribute of the enclosure element:
echo 'Enclosure Url: ', $xpath->evaluate('string(enclosure/#url)', $rssItem), "\n";
Related
To be short - the code works.
But how ?
I made a PHP curl so scrape a website and get some events. Works.
Then i wanted to group some scraped events together. Tested some variations and to the end i did this:
$communities[$current_color][] = $li->plaintext;
Works. But i cant imagine how this is a grouping function....
Anyone an idea?
Here is the most important of my code:
echo '<article class="month">';
foreach( $html->find('tr') as $tr ){
$montName = $tr->find('.ev_td_left', 0);
echo '<h3>' . $montName->plaintext . '</h3>';
echo '<ul>';
foreach( $tr->find('li') as $li ){
$style = $li->style;
preg_match( "/#.{6}/", $style, $li_bgcolor );
/**
* Array nach Farben gruppieren
*/
$current_color = $li_bgcolor[0];
$communities[$current_color][] = $li->plaintext;
echo '<li><span class="event" style="background-color:'.$li_bgcolor[0].';"></span>'.$li->plaintext.'</li>';
}
echo '</ul>';
echo '<br/>';
}
echo '</article>';
I think I'm picking this up pretty well, but I'm just stuck on this. I want to display this menu using an array and foreach loop:
<img src="/img/page-icons/credit-card21.png" />Payments
<a target="_blank" href="/cloud"><img src="/img/page-icons/upload123.png" />Cloud</a>
<a target="_blank" href="/portal"><img src="/img/page-icons/earth208.png" />Portal</a>
So to do that I need to turn that into this line in PHP:
echo '<img src="/img/page-icons/' . $image . '" />' . $title . '';
To fill that out in the loop we need to create something like this... which is where I'm stuck:
foreach( $stamp as $link => $target ){
echo '<a href="/' . $link . '" target="' . $target . '">';
foreach( $stamp[] as $title => $image ){
echo '<img src="/img/page-icons/' . $image . '" />' . $title;
}
echo '</a>';
}
I don't really know how to go about the above, just been messing around with it for a while today. I also don't want to always display target="' . $target . '" on every link.
The array would probably be a two dimensional array? Something like this any way:
$stamp = array(
'link' => array('title' => 'image'),
'link' => array('title' => 'image'),
'link' => array('title' => 'image')
);
EDIT:
There's some confusion of what 'target' is, I want to echo 4 values from an array into a link, target is one of the values. I didn't know how to use that in the array so I just left it out.
When you do:
foreach( $stamp as $link => $target )
The $link variable contains the string "link" and the $target variable is an array such as ['title' => 'image'].
What you should probably do is have an array like this:
// Init links
$links = array();
// Add links
$links[] = array(
'title' => 'My Title',
'href' => 'http://www.google.com',
'target' => '_blank',
'image' => 'image.png',
);
foreach ($links as $link)
{
echo '<a href="'.$link['href'].'" target="'.$link['target'].'">';
echo '<img src="/img/page-icons/' . $link['image'] . '" />';
echo $link['title'];
echo '</a>';
}
This is a bit more flexible approach that lets you add other data items to the structure in the future. That $links array could easily be generated in a loop if you have a different data source such as a database as well.
EDIT
To answer your further question, you can prefix the link building with a set of sane defaults like this:
foreach ($links as $link)
{
// Use the ternary operator to specify a default if empty
$href = empty($link['href']) ? '#' : $link['href'];
$target = empty($link['target']) ? '_self' : $link['target'];
$image = empty($link['image']) ? 'no-icon.png' : $link['image'];
$title = empty($link['title']) ? 'Untitled' : $link['title'];
// Write link
echo "<a href='$href' target='$target'>";
echo "<img src='/img/page-icons/$image' />";
echo $title;
echo "</a>";
}
you can set your array like:
$stamp = array(
'0' => array('title'=>$title 'image'=>$image,'link'=>$link,'target'=>$target),
'1' => array('title'=>$title, 'image'=>$image,'link'=>$link,,'target'=>$target),
'2' => array('title'=>$title 'image'=>$image,'link'=>$link,'target'=>$target)
);
and in foreach you can write
$i=0;
foreach( $stamp as $st=> $target ){
echo '<a href="/' . $st['link'] . '" target="' . $st['target'] . '">';
echo '<img src="/img/page-icons/' . $st['image'] . '" />' . $st['title'];
echo '</a>';
}
I got an error saying
Object of class DOMNodeList could not be converted to string on line
This is the line which contains the error:
$output .= '<li><a target="_blank" href="' . $postURL . '">' .
$title->nodeValue . '</a></li>';
DOM
My code:
$postTitle = $xpath->query("//tr/td[#class='row1'][3]//span[1]/text()");
$postURL = $xpath->query("//tr/td[#class='row1'][3]//a/#href");
$output = '<ul>';
foreach ($postTitle as $title) {
$output .= '<li><a target="_blank" href="' . $postURL . '">' . $title->nodeValue . '</a></li>';
}
$output .= '</ul>';
echo $output;
How can I resolve the error?
You're fetching two independent node list from the DOM, iterate the first and try to use the second one inside the loop as a string. A DOMNodeList can not be cast to string (in PHP) so you get an error. Node lists can be cast to string in Xpath however.
You need to iterate the location path that is the same for booth list (//tr/td[#class='row1'][3]) and get the $title and $url inside the loop for each of the td elements.
$posts = $xpath->evaluate("//tr/td[#class='row1'][3]");
$output = '<ul>';
foreach ($posts as $post) {
$title = $xpath->evaluate("string(.//span[1])", $post);
$url = $xpath->evaluate("string(.//a/#href)", $post);
$output .= sprintf(
'<li><a target="_blank" href="%s">%s</a></li>',
htmlspecialchars($url),
htmlspecialchars($title)
);
}
$output .= '</ul>';
echo $output;
I'm getting category from my database using PHP and I want to use it inside Google Analytics event tracking code. The problem is that events are not being recorded in Google Analytics.
Here are some code snippets from my project:
1)
$docs = array();
while ($row = mysql_fetch_assoc($result)) {
$doc = array();
$doc['my_tel'] = $row['my_tel'];
$doc['my_category'] = $row['my_category'];
$docs[] = $doc;
}
mysql_free_result($result);
2)
<?php
$html_output = '';
foreach ($docs as &$d) {
$html_output .= '<div>' .
'<img src="call.png" width="65px" height="35px" border="0">' .
'</div>';
}
echo $html_output;
?>
If you have a look at the console of your browser there might be a JavaScript error, because the second parameter of _gaq.push is not wrapped with quotes.
Try this:
<?php
$html_output = '';
foreach ($docs as &$d) {
$html_output .= '<div>' .
'<img src="call.png" width="65px" height="35px" border="0">' .
'</div>';
}
echo $html_output;
?>
Looking at your append to $html_output, it appears you're not enclosing the category within single quotes in the resultant javascript output.
Assuming for example my_tel was 01234567890 and category was 'Category 1' the output from the code above would be:
<div><img src="call.png" width="65px" height="35px" border="0"></div>
Perhaps try (note additional escaped quotes around category:
'<a href="tel:' . $d['my_tel'] . '" onClick="_gaq.push([\'_trackEvent\', \'' . $d['my_category'] . '\', \'Event Action\',...
--dan
I have a fetch function that injects rss content into a page for me. This returns an xml which contains the usual RSS elements like title, link, description but the problem is the returned description is a table with two tds which one contains an image the other the text. I am not sure how I can remove the table, img and the tds and be left only with the text using php and not javascript.
Any help is much appreciated.
<?php
require_once('rss_fetch.inc');
$url = 'http://www.domain.com/rss.aspx?typeid=0&imagesize=120&topcount=20';
if ( $url ) {
$rss = fetch_rss( $url );
//echo "Channel: " . $rss->channel['title'] . "<p>";
echo "<ul>";
foreach ($rss->items as $item) {
$href = $item['link'];
$title = $item['title'];
$description = $item['description'];
$pubdate = date('F dS, Y', strtotime($item['pubdate']));
echo "<li><h3>$title<em>$pubdate</em></h3>$description <p><a href='$href' target='_blank'>ادامه مطلب</a></p><br/></li>";
}
echo "</ul>";
}
?>
strip_tags() will do the job..