How to turn variable feed to array? - php

I want to turn the variable into an array so I can store more than one feed?
<?php
error_reporting(0);
$feed_lifehacker_full = simplexml_load_file('http://feeds.gawker.com/lifehacker/full');
$xml = $feed_lifehacker_full;
//print_r($xml);
foreach ($xml->channel->item as $node){
$title = $node->title;
$link = $node->link;
$link = explode('/', $link);
$link = $link[8];
$url = $node->url;
$description = $node->description;
$pubDate = $node->pubDate;
preg_match_all('#(http://img[^\s]+(?=\.(jpe?g|png|gif)))#i', $description[0], $images);
$images = $images[0][1] . '.jpg';
if($images == '.jpg'){
//uncomment to show youtube articles
//$images = "http://placehold.it/640x360";
//echo "<a href='page2.php?a=$link' title='$title'><img src='$images' /></a><br>";
} else {
//article image
$images . '<br>';
echo "<a href='page2.php?a=$link' title='$title'><img src='$images' /></a><br>";
}
}
How can I change this to load to arrays,
$feed_lifehacker_full = simplexml_load_file('http://feeds.gawker.com/lifehacker/full');
$xml = $feed_lifehacker_full;
The script is just gathering the image of an rss feed and linking to a page, if you see how it can be done more efficiently feel free to say

it is possible to encode the result given as json and by decoding it it will return you an array
$xml = simplexml_load_string($xmlstring);
$json = json_encode($xml);
$array = json_decode($json, TRUE);

Related

json file_get_contents and show item

I have this code but I can't make the items to show properly, I can only show the data from echo $data sentence but not $item FirstName or Item Bio
$url = 'https://jdublu.com/api/wrsc/json_employee.php?RID=17965'; // path to your JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
$items = json_decode($data, true);
foreach ($items as $item)
{
$name = $item = ["FirstName"];
$bio = $item = ["Bio"];
}
echo $data
if you see the json response it has 2 elements.
{
message : ...,
department : ....
}
so you have to loop throw $items['department'] rather than $items
and you can access the data like $item['Bio']
So you can change the code like this to get the information
<?php
$url = 'https://jdublu.com/api/wrsc/json_employee.php?RID=17965';
$data = file_get_contents($url); // into a variable
$items = json_decode($data, true); // decode the JSON feed
foreach ($items['department'] as $item)
{
$name = $item["FirstName"];
$bio = $item["Bio"];
echo $name . ' ' . $bio . PHP_EOL;
}

returning json array with PHP not working

I am trying to return a json array after i parse an rss feed.
this is my code :
<?php
header('Content-Type: application/json');
$feed = new DOMDocument();
//http://www.espnfc.com/rss
//http://www.football365.com/topical-top-10/rss
$feed->load('http://www.espnfc.com/rss');
$json = array();
$items = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('item');
$json['item'] = array();
$i = 0;
foreach($items as $item) {
$i = $i+1;
$title = $item->getElementsByTagName('title')->item(0)->firstChild->nodeValue;
$link = $item->getElementsByTagName('link')->item(0)->firstChild->nodeValue;
$img = $item->getElementsByTagName('enclosure')->item(0)->attributes->getNamedItem('url')->value;
//$img = $item;echo($url);
$json['item'][] = array("title"=>str_replace(array("\n", "\r", "\t","'"), ' ', $title),"link"=>str_replace(array("\n", "\r", "\t","'"), ' ', $link),"img"=>str_replace(array("\n", "\r", "\t","'"), ' ', $img));
}
print_r($json['item'][0]);
//echo json_encode($json['item']);
?>
after iterating all items i finally would like to echo them as a result:
echo json_encode($json['item']);
the problem that's not showing any thing in browser. but when i moved this line into the foreach bloc it show result (of course with redundancy).
Some of the items don't have an <enclosure> tag, so the script gets an error when it tries to access the url attribute. You need to check for this.
$enclosures = $item->getElementsByTagName('enclosure');
if ($enclosures->length) {
$img = $item->getElementsByTagName('enclosure')->item(0)->attributes->getNamedItem('url')->value;
} else {
$img = '';
}
Your code returns request status "Status Code:500 Internal Server Error"
You can easy see it by browsing the network tab of your browser's web tools.
This is because on the 3rd post there is no image.
<?php
// Json Header
header('Content-Type: application/json');
// Get Feed
$feed = new DOMDocument();
$feed->load('http://www.espnfc.com/rss');
// Get Items
$items = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('item');
// My json object
$json = array();
$json['item'] = array();
// For each item
foreach($items as $item){
// Get title
$title = $item->getElementsByTagName('title')->item(0)->firstChild->nodeValue;
// Get link
$link = $item->getElementsByTagName('link')->item(0)->firstChild->nodeValue;
// Get image if it exist
$img = $item->getElementsByTagName('enclosure');
if($img->length>0){
$img = $img->item(0)->attributes->getNamedItem('url')->value;
} else {
$img = "";
}
array_push($json['item'], array(
"title" => preg_replace('/(\n|\r|\t|\')/', ' ', $title),
"link" => preg_replace('/(\n|\r|\t|\')/', ' ', $link),
"img" => preg_replace('/(\n|\r|\t|\')/', ' ', $img)
));
}
echo json_encode($json['item']);
?>

PHP foreach with two 'as'?

Hi there i am trying to combine two loops of foreach but i have a problem.
The problem is that the <a href='$link'> is same to all results but they must be different.
Here is the code that i am using:
<?php
$feed = file_get_contents('http://grabo.bg/rss/?city=&affid=16090');
$rss = simplexml_load_string($feed);
$doc = new DOMDocument();
#$doc->loadHTML($feed);
$tags = $doc->getElementsByTagName('link');
foreach ($tags as $tag) {
foreach($rss as $r){
$title = $r->title;
$content = $r->content;
$link = $tag->getAttribute('href');
echo "<a href='$link'>$title</a> <br> $content";
}
}
?>
Where i my mistake? Why it's not working and how i make it work properly?
Thanks in advance!
Both loops were going through different resources so you are just simply cross joining all records in them.
This should work to get the data you need:
<?php
$feed = file_get_contents('http://grabo.bg/rss/?city=&affid=16090');
$rss = simplexml_load_string($feed);
foreach ($rss as $key => $entry) {
if ($key == "entry")
{
$title = (string) $entry->title;
$content = (string) $entry->content;
$link = (string) $entry->link["href"];
echo "<a href='$link'>$title</a><br />" . $content;
}
}

Getting XML attributes in PHP

Looked at a few other SO posts on this but no joy.
I've got this code:
$url = "http://itunes.apple.com/us/rss/toppaidapplications/limit=10/genre=6014/xml";
$string = file_get_contents($url);
$string = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $string);
$xml = simplexml_load_string($string);
foreach ($xml->entry as $val) {
echo "RESULTS: " . $val->attributes() . "\n";
but I can't get any results.
I'm specifically interested in getting the ID value which would be 549592189 in this fragment:
<id im:id="549592189" im:bundleId="com.activision.wipeout">http://itunes.apple.com/us/app/wipeout/id549592189?mt=8&uo=2</id>
Any suggestions?
SimpleXML gives you can easy way to drill down in the XML structure and get the element(s) you want. No need for the regex, whatever it does.
<?php
// Load XML
$url = "http://itunes.apple.com/us/rss/toppaidapplications/limit=10/genre=6014/xml";
$string = file_get_contents($url);
$xml = new SimpleXMLElement($string);
// Get the entries
$entries = $xml->entry;
foreach($entries as $e){
// Get each entriy's id
$id = $e->id;
// Get the attributes
// ID is in the "im" namespace
$attr = $id->attributes('im', TRUE);
// echo id
echo $attr['id'].'<br/>';
}
DEMO: http://codepad.viper-7.com/qNo7gs
Try with xpath:
$doc = new DOMDocument;
#$doc->loadHTML($string);
$xpath = new DOMXpath($doc);
$r = $xpath->query("//id/#im:id");
$id = $r->item(0)->value;
Try:
$sxml = new SimpleXMLElement($url);
for($i = 0;$i <=10;$i++){
$appid= $sxml->entry[$i]->id->attributes("im",TRUE);
echo $appid;
}

Getting random post from rss feed

I have an rss feed, created by Yahoo Pipes and I need to get random post from it. How is it possible to realize this on php?
Read the feed using XML Parser and put it in an array. then, use array_rand to pick a random item from the array.
<?
function load_xml_feed($feed)
{
global $RanVal;
$i= 1;
$FeedXml = simplexml_load_file($feed);
foreach ($FeedXml->channel->item as $topic) {
$title[$i] = (string)$topic->title;
$link[$i] = (string)$topic->link;
$description[$i] = (string)$topic->description;
$i++;
}
$randtopic = rand(2, $i);
$link = trim($link[$randtopic]);
$title = trim($title[$randtopic]);
$description = trim($description[$randtopic]);
$RanVal = array($title,$link,$description);
return $RanVal;
}
$rss = "http://www.sabaharabi.com/rss/rss.xml";
load_xml_feed($rss);
$link = $RanVal[1];
$title = $RanVal[0];
$description = $RanVal[2];
echo "<h1>".$title."</h1><h2>".$link."</h2><p>".$description."</p>";

Categories