I want to display a random image from the Unsplash.com RSS feed (https://unsplash.com/rss) using PHP. I've read about how to this, but I can't seem to quite understand it. I think the easiest way to do this is would be with SimpleXML. Then I'd like to use the image as a background-image for my website. Can anyone help me out with this? Thanks!
Try this :
function getRandomImageFromRSS($url = 'https://unsplash.com/rss')
{
$xml = simplexml_load_file($url);
$images = array();
foreach ($xml->channel->item as $item)
{
foreach ($item->image->url as $url)
{
$images[] = (string) $url;
}
}
shuffle($images);
return isset($images[0]) ? $images[0] : null;
}
echo getRandomImageFromRSS();
Related
I'm trying to write a script that list all the image URL from an specific URL. I used foreach in order to scan several pages, but I think os not working well.
This is my code:
<?php
include('simple_html_dom.php');
$array = array($page, $page2);
$page = "https://www.dllo.dev";
$page2 = "https://www.dllo2.dev";
$html = new simple_html_dom();
$html->load_file($array);
$images = array();
foreach($html->find('img') as $element) {
$images[] = $element->src;
}
reset($images);
echo "URL $array:<br /><br />";
foreach ($images as $out) {
$url = "$base$out";
echo "$url, ";
}
It's partially working, but only with the first URL ($page)... Any idea?
:D
I am somewhat new with PHP, but can't really wrap my head around what I am doing wrong here given my situation.
Problem: I am trying to get the href of a certain HTML element within a string of characters inside an XML object/element via Reddit (if you visit this page, it would be the actual link of the video - not the reddit link but the external youtube link or whatever - nothing else).
Here is my code so far (code updated):
Update: Loop-mania! Got all of the hrefs, but am now trying to store them inside a global array to access a random one outside of this function.
function getXMLFeed() {
echo "<h2>Reddit Items</h2><hr><br><br>";
//$feedURL = file_get_contents('https://www.reddit.com/r/videos/.xml?limit=200');
$feedURL = 'https://www.reddit.com/r/videos/.xml?limit=200';
$xml = simplexml_load_file($feedURL);
//define each xml entry from reddit as an item
foreach ($xml -> entry as $item ) {
foreach ($item -> content as $content) {
$newContent = (string)$content;
$html = str_get_html($newContent);
foreach($html->find('table') as $table) {
$links = $table->find('span', '0');
//echo $links;
foreach($links->find('a') as $link) {
echo $link->href;
}
}
}
}
}
XML Code:
http://pasted.co/0bcf49e8
I've also included JSON if it can be done this way; I just preferred XML:
http://pasted.co/f02180db
That is pretty much all of the code. Though, here is another piece I tried to use with DOMDocument (scrapped it).
foreach ($item -> content as $content) {
$dom = new DOMDocument();
$dom -> loadHTML($content);
$xpath = new DOMXPath($dom);
$classname = "/html/body/table[1]/tbody/tr/td[2]/span[1]/a";
foreach ($dom->getElementsByTagName('table') as $node) {
echo $dom->saveHtml($node), PHP_EOL;
//$originalURL = $node->getAttribute('href');
}
//$html = $dom->saveHTML();
}
I can parse the table fine, but when it comes to getting certain element's values (nothing has an ID or class), I can only seem to get ALL anchor tags or ALL table rows, etc.
Can anyone point me in the right direction? Let me know if there is anything else I can add here. Thanks!
Added HTML:
I am specifically trying to extract <span>[link]</span> from each table/item.
http://pastebin.com/QXa2i6qz
The following code can extract you all the youtube links from each content.
function extract_youtube_link($xml) {
$entries = $xml['entry'];
$videos = [];
foreach($entries as $entry) {
$content = html_entity_decode($entry['content']);
preg_match_all('/<span><a href="(.*)">\[link\]/', $content, $matches);
if(!empty($matches[1][0])) {
$videos[] = array(
'entry_title' => $entry['title'],
'author' => preg_replace('/\/(.*)\//', '', $entry['author']['name']),
'author_reddit_url' => $entry['author']['uri'],
'video_url' => $matches[1][0]
);
}
}
return $videos;
}
$xml = simplexml_load_file('reddit.xml');
$xml = json_decode(json_encode($xml), true);
$videos = extract_youtube_link($xml);
foreach($videos as $video) {
echo "<p>Entry Title: {$video['entry_title']}</p>";
echo "<p>Author: {$video['author']}</p>";
echo "<p>Author URL: {$video['author_reddit_url']}</p>";
echo "<p>Video URL: {$video['video_url']}</p>";
echo "<br><br>";
}
The code outputs in the multidimensional format of array with the elements inside are entry_title, author, author_reddit_url and video_url. Hope it helps you!
If you're looking for a specific element you don't need to parse the whole thing. One way of doing it could be to use the DOMXPath class and query directly the xml. The documentation should guide you through.
http://php.net/manual/es/class.domxpath.php .
I am using the below code to fetch the $movie->id from the response XML
<?php
$movie_name='Dabangg 2';
$url ='http://api.themoviedb.org/2.1/Movie.search/en/xml/accd3ddbbae37c0315fb5c8e19b815a5/%22Dabangg%202%22';
$xml = simplexml_load_file($url);
$movies = $xml->movies->movie;
foreach ($movies as $movie){
$arrMovie_id = $movie->id;
}
?>
the response xml structure is
How to fetch image URL with thumb size?
See the below an easy way to get only specific images.
$xml = simplexml_load_file($url);
$images = $xml->xpath("//image");
//echo "<pre>";print_r($images);die;
foreach ($images as $image){
if($image['size'] == "thumb"){
echo "URL:".$image['url']."<br/>";
echo "SIZE:".$image['size']."<br/>";
echo "<hr/>";
}
}
Use the attributes() method of SimpleXmlElement.
Example:
$imageAttributes = $movie->images[0]->attributes();
$size = $imageAttributes['size'];
See the documentation at: http://www.php.net/manual/en/simplexmlelement.attributes.php
EDIT: select only URL attributes with size = "thumb" and type = "poster":
$urls = $xml->xpath("//image[#size='thumb' and #type='poster']/#url");
if you expect only 1 url, do:
$url = (string)$xml->xpath("//image[#size='thumb' and #type='poster']/#url")[0];
echo $url;
working live demo: http://codepad.viper-7.com/wdmEay
I'm building a PHP program that basically grabs only image links from my twitter feed and displays them on a page, I have 3 components that I have set up that all work fine on their own.
The first component is the twitter oauth component which grabs the tweet text and creates an array, this works fine by itself.
The second is a function that processes the tweets and only returns tweets that contain image links, this as well works fine.
The program breaks down during the third section when the links are processed and an image is displayed, I had no issues running this on its own and from my attempts to trouble shoot it appears that it breaks down at the $images(); array, as that array is empty.
I'm sure I've made a silly mistake but I've been trying to find this for over a day now and can't seem to fix it. Any help would be great! Thanks guys!
code:
<?php
if ($result['socialorigin']== "twitter"){
$twitterObj = new EpiTwitter($consumer_key, $consumer_secret);
$token = $twitterObj->getAccessToken();
$twitterObj->setToken($result['oauthtoken'], $result['oauthsecret']);
$tweets = $twitterObj->get('/statuses/home_timeline.json',array('count'=>'200'));
$all_tweets = array();
$hosts = "lockerz|yfrog|twitpic|tumblr|mypict|ow.ly|instagr";
foreach($tweets as $tweet) {
$twtext = $tweet->text;
if(preg_match("~http://($hosts)~", $twtext)){
preg_match_all("#(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t<]*)#ise", $twtext, $matches, PREG_PATTERN_ORDER);
foreach($matches[0] as $key2 => $link){
array_push($all_tweets,"$link");
}
}
}
function height_compare($a1, $b1)
{
if ($a1 == $b1) {
return 0;
}
return ($a1 > $b1) ? -1 : 1;
}
foreach($all_tweets as $alltweet => $tlink){
$doc = new DOMDocument();
// Okay this is HTML is kind of screwy
// So we're going to supress errors
#$doc->loadHTMLFile($tlink);
// Get all images
$images_list = $doc->getElementsByTagName('img');
$images = array();
foreach($images_list as $image) {
// Get the src attribute
$image_source = $image->getAttribute('src');
if (substr($image_source,0,7)=="http://"){
$image_size_info = getimagesize($image_source);
$images[$image_source] = $image_size_info[1];
}
}
// Do a numeric sort on the height
uasort($images, "height_compare");
$tallest_image = array_slice($images, 0,1);
$mainimg = key($tallest_image);
echo "<img src='$mainimg' />";
}
print_r($all_tweets);
print_r($images);
}
Change the for loop where you fetch the actual images to move the images array OUTSIDE the for loop. This will prevent the loop from clearing it each time through.
$images = array();
foreach($all_tweets as $alltweet => $tlink){
$doc = new DOMDocument();
// Okay this is HTML is kind of screwy
// So we're going to supress errors
#$doc->loadHTMLFile($tlink);
// Get all images
$images_list = $doc->getElementsByTagName('img');
foreach($images_list as $image) {
// Get the src attribute
$image_source = $image->getAttribute('src');
if (substr($image_source,0,7)=="http://"){
$image_size_info = getimagesize($image_source);
$images[$image_source] = $image_size_info[1];
}
}
// Do a numeric sort on the height
uasort($images, "height_compare");
$tallest_image = array_slice($images, 0,1);
$mainimg = key($tallest_image);
echo "<img src='$mainimg' />";
}
I am Parsing XML currently using:
$data = simplexml_load_string($xmlFile);
foreach($data->item as $key => $current){
echo($current);
}
However I'm wondering, if a hit an element that looks like this:
<thumbnail url="http://foo.bar" height="225" width="300"/>
How do i pull the inner parts of this? (height, url, width)
Thanks!
foreach($data->item->thumbnail as $thumbnail) {
$url = $thumbnail['url'];
$height = $thumbnail['height'];
$width = $thumbnail['width'];
}
In case you don't know how many attributes there will be...
foreach ($data->item->thumbnail->attributes() as $key => $value) {
$attr[$key] = (string)$value;
}