php reader google new - php

I installed a php reader for Google News on my website to read the first five articles but (1) the images don't display, and (2) I would like only the first source article of the master title.
$news = simplexml_load_file('https://news.google.com/news?q=guadeloupe&output=rss&hl=fr&ned=fr&num=5');
$feeds = array();
$i = 0;
foreach ($news->channel->item as $item)
{
$parts = explode('<td', $item->description);
$titre = explode('<div class="lh">', $item->description);
$feeds[$i]['description'] = (string) $item->description;
$feeds[$i]['title'] = (string) $item->title;
$feeds[$i]['link'] = (string) $item->link;
if (isset($parts[1])) {
$feeds[$i]['site_title'] = strip_tags($parts[1]);
}
$RSS_title = (string) $item->title;
$RSS_link = (string) $item->link;
if (isset($parts[2])) {
$RSS_part2 = $parts[2];
$RSS_part2 = str_replace('valign="top" class="j">','',$RSS_part2);
$RSS_part2 = str_replace('<a href=','<a class="lienviolet15B" style="font-size:14px;" target="_blank" href=',$RSS_part2);
echo "$RSS_part2";
}
$i++;
}

RiggsFolly, num=1 list only one news and i want 5 news ;)
i found the solution and give my code for a php google news reader on specific query :
<?php
// clean cut function
function cleanCut($string,$length,$cutString = '...'){
if(strlen($string) <= $length) {
return $string; }
$str = substr($string,0,$length-strlen($cutString)+1);
return substr($str,0,strrpos($str,' ')).$cutString;
}
//// google news => list 5 news on special query, here "formule 1"
//// if query have space or special chars use urlencode($myquery)
//// replace language value in rss url (here "fr" for french)
$myquery = "formule 1";
$myquery = urlencode($myquery);
$news = simplexml_load_file('https://news.google.com/news?q='.$myquery.'&output=rss&hl=fr&ned=fr&num=5');
$feeds = array();
$i = 0;
foreach ($news->channel->item as $item) {
preg_match('#src="([^"]+)"#', $item->description, $match);
$parts = explode('<font size="-1">', $item->description);
$feeds[$i]['title'] = (string) $item->title;
$feeds[$i]['link'] = (string) $item->link;
$feeds[$i]['image'] = $match[1];
$feeds[$i]['site_title'] = strip_tags($parts[1]);
$feeds[$i]['story'] = strip_tags($parts[2]);
$i++;
$RSS_title = (string) $item->title;
$RSS_title = substr($RSS_title, 0, strpos($RSS_title, "-")); // delete source site in title
$RSS_title = cleanCut($RSS_title, 60); // (option) clean cut title after 60 char
$RSS_link = (string) $item->link; // extract link
$RSS_story = strip_tags($parts[2]); // extract begin article
$RSS_story = cleanCut($RSS_story, 260); // (option) clean cut article after 260 char
$RSS_image = $match[1]; // extract image
$RSS_source = strip_tags($parts[1]); // extract source site
if ($RSS_image!="") { // only article with image
echo "<div class=\"row\" style=\"margin-bottom:20px;\">";
echo "<div class=\"col-xs-12\">";
echo "<img src=\"".$RSS_image."\" style=\"width:80px;float:left;margin:0px 10px\">";
echo "<a class=\"lienviolet15B\" style=\"font-size:14px;\" target=\"_blank\" href=\"".$RSS_link."\">";
echo "".$RSS_title."";
echo "</a><br>";
echo "".$RSS_story."<br>";
echo "<div class=\"pull-right\"><i>".$RSS_source."</i></div>";
echo "</div></div>";
}
}
//echo '<pre>'; print_r($feeds); echo '</pre>'; // rss brut
?>

Related

PHP file unable to extract and split image from database after made changes to the file

I have this issue on one of servers, Up until last week, the feed it was pulling the content from was working fine. Now suddenly since last few days, when I made the change to extract category field from database since then it is not extracting the image from the feed but is able to extract all of other content. (This server was set up by previous developer).
I keep getting this error:
going to get file 2020-07-23T15:41:05
going to put /var/www/SpanishMix/
!! problem getting remote file ( 2020-07-23T15:41:05 ) in checkNGet ** trying replace , digiv/2105318.jpg
This is the code in php file:
<?php
set_time_limit(90);
ini_set('memory_limit', '128M');
$xurl = 'feedlink.com/feed/getXML.php';
$locs = 'server ip';
$locvid = '/var/www/SpanishMix/';
function decrypto($inStr)
{
$key = '';
$encrypted = $inStr;
$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($encrypted), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
return $decrypted;
}
function dis($v)
{
echo "<pre>\n";
print_r($v);
echo "\n</pre>\n<hr>\n";
}
// --------------------- grab XML
$c = file_get_contents($xurl);
if (strlen($c) < 100) {
exit('couldnt get data from CMS');
}
// --------------------- parse into usable array of objects
$sa = array();
$ta1 = explode('_ENDI_', $c);
foreach ($ta1 as $i) {
$ta2 = explode('_ENDF_', $i);
if ((strlen($ta2[0]) > 4) && (strlen($i) > 200)) {
$to = new stdClass();
$to->uid = $ta2[0];
$to->vurl = "";
$to->body = $ta2[1];
$to->people = trim($ta2[2]);
$to->headline = trim($ta2[3]);
$to->category = trim($ta2[4]);
$to->abstract = trim($ta2[5]);
$to->pubdate = trim($ta2[7]);
$to->storyid = trim($ta2[6]);
$to->iurl = trim($ta2[8]);
$tmpia = explode('.com/', $to->iurl);
$to->cpi = $tmpia[1];
$to->iloc = 'http://' . $locs . '/SpanishMix/' . $tmpia[1];
// code for durability date
$tmpda = explode('-', $to->pubdate);
$oldy = $tmpda[0];
$newy = $oldy + 1;
$newys = str_replace($oldy, $newy, $to->pubdate);
$to->durdate = $newys;
$to->gotv = 0;
$to->fs = 0;
if ($to->uid > 10000) {
$sa[$to->uid] = $to;
}
}
}
dis($sa);
// --------------------- scan vids dir, parse into array including filesize
$va = array();
$dir = $locvid . "*.jpg";
foreach (glob($dir) as $file) {
$tv = new stdClass();
$tv->fn = $file;
$tv->s = filesize($file);
array_push($va, $tv);
}
dis($va);
// --------------------- check through stories array structure marking those already with video
$vtg = '';
$itg = '';
$uidtg = '';
// loop through each story
foreach ($sa as $s) {
$found = 0;
foreach ($va as $v) {
// hack out matchable filename from video and story arrays
$tfn = '/var/www/SpanishMix/' . $s->cpi;
if ($tfn == $v->fn) {
$found = 1;
}
}
// if outer looop variable says no video found for this story, make this storey's video URL next to get
if (!$found) {
echo "<br>setting itg to $s->iurl<br>\n";
$itg = $s->iurl;
$uidtg = $s->uid;
}
}
echo "<hr><h1> getting video part</h1><br><br>";
// --------------------- elect first story entry with no file
if ($itg) {
// split img url to take
$ifa = explode('.com/', $itg);
$itg = $itg;
$outfile = '/var/www/SpanishMix/' . $ifa[1];
echo "\n<br><b>going to get file $itg<br>going to put $outfile</b><br>\n";
$remoteFile = file_get_contents($itg);
if (!$remoteFile) {
echo "!! problem getting remote file ( $itg ) in checkNGet\n\n";
} else {
$res = file_put_contents($outfile, $remoteFile);
if ($res) {
echo "put remote image file ( $outfile ) success !\n\n\n";
// NOW COPY LOCAL FILE TO FUNNY FILENAME
$cpifn = '/var/www/SpanishMix/digiv/' . $uidtg . '.jpg';
echo "* about to copy $outfile to $cpifn\n\n";
copy($outfile, $cpifn);
} else {
echo "put remote image file ( $outfile ) fail :( \n\n\n<br><br>";
}
}
}
$tt = '';
$tm = '<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<videonews>
<news>
<name>BBCC**storyid**</name>
<title>**headline**</title>
<subtitle>**abstract**</subtitle>
<text>**body**</text>
<keywords>**people**</keywords>
<date>**pubdate**</date>
<durability>**durdate**</durability>
<category>**category**</category>
<subcategory>Famosos</subcategory>
<image>
<file format="image">**iloc**</file>
</image>
</news>
</videonews>
';
$tb = '';
$out = $tt;
foreach ($sa as $s) {
if ($s->uid == $uidtg) {
$tfn = "$locs/SpanishMix/" . $tfna[3];
$tmpt = str_replace('**body**', $s->body, $tm);
//$tmpt = str_replace('**vidfs**', $s->fs, $tmpt);
$tmpt = str_replace('**headline**', $s->headline, $tmpt);
$tmpt = str_replace('**people**', $s->people, $tmpt);
$tmpt = str_replace('**abstract**', $s->abstract, $tmpt);
$tmpt = str_replace('**storyid**', $s->storyid, $tmpt);
$tmpt = str_replace('**category**', $s->category, $tmpt);
$tmpt = str_replace('**pubdate**', $s->pubdate, $tmpt);
$tmpt = str_replace('**durdate**', $s->durdate, $tmpt);
$tmpt = str_replace('**iloc**', $s->iloc, $tmpt);
$copyA2 = explode('SpanishMix/', $s->iloc);
$copyImageFN = $copyA2[1];
$copyNewImageFN = 'digiv/' . $uidtg . '.jpg';
echo "\n ** trying replace $copyImageFN, $copyNewImageFN\n";
$tmpt = str_replace($copyImageFN, $copyNewImageFN, $tmpt);
$out .= "$tmpt\n\n";
}
}
$out .= $tb;
if ($uidtg) {
echo "</pre><TEXTAREA cols='120' rows='80'>$out</TEXTAREA>\n";
echo "<hr>";
$ox = '/var/www/SpanishMix/digiv/' . $uidtg . '.xml';
$written = file_put_contents($ox, $out);
echo "\nALSO putting : xml to $ox [", $written, "]<br>\n";
} else {
echo "\n NO UIDTG [", $uidtg, "] ! \n not putting any files";
}
I would really appreciate some help on this.

Get Tumbnail with google news rss feed using php

I can not get the tumbnail images using the following code. What i need to do to get a tumbnail images from google rss feed. Anyone can help me please ?
$news = simplexml_load_file('https://news.google.com/news?pz=1&cf=all&ned=en&hl=en&topic=n&output=rss');
$feeds = array();
$i = 0;
foreach ($news->channel->item as $item)
{
preg_match('~<img[^>]*src\s?=\s?[\'"]([^\'"]*)~i',$item->description, $imageurl);
//preg_match('#src="([^"]+)"#', $item->description, $imageurl);
$parts = explode('<font size="-1">', $item->description);
$feeds[$i]['title'] = (string) $item->title;
$feeds[$i]['link'] = (string) $item->link;
$feeds[$i]['image'] = $imageurl[1];
$feeds[$i]['site_title'] = strip_tags($parts[1]);
$feeds[$i]['story'] = strip_tags($parts[2]);
$i++;
}
echo '<pre>';
print_r($feeds);
echo '</pre>';

Show RSS feed items based on other PHP script

I want to create an RSS feed in PHP based on other RSS feeds. That works.
But, Now I want to change how many items are shown in the new created feed. This based on calculation of the items of another feed.
I use this script for the calculation, which works fine:
<?php
$url = 'http://www.nu.nl/rss/Algemeen';
$xml = simplexml_load_file($url);
$tags = array();
foreach($xml->channel->item as $item) {
$children = $item->children(); // get all children of each item tag
foreach ($children as $node) {
$tags[] = $node->getName(); // get the node name of each children
}
}
$test = count($tags);
$count = array_count_values($tags); // count the values
?>
<?php
$mystring = count($tags);
$findme = '3';
$pos = strpos($mystyring, $findme);
?>
<?php
$artikel = ($mystring / 5);
echo $artikel;
?>
I use this script, magpierss, fow creating a new feed:
<?php
/**
* Setup
*
*/
$DOMAIN_NAME = 'http://sitename.nl/';
$FEED_URL = $DOMAIN_NAME . 'rss/full.php';
$SITE_TITLE = 'test';
$SITE_DESRIPTION = '-';
$SITE_AUTHOR = 'test2';
$RSS_CACHE = "/tmp/rsscache";
$RSS_CACHE_EXP = 3600;
$FEED_LIST = array(
'http://www.nu.nl/rss/Economie',
'http://www.nu.nl/rss/Internet'
);
/**
* Do not modify below this point
*
*/
define('MAGPIE_CACHE_DIR', $RSS_CACHE);
define('MAGPIE_CACHE_AGE', $RSS_CACHE_EXP);
define('MAGPIE_OUTPUT_ENCODING', 'utf-8');
// include required files
require_once ('magpierss-0.72/rss_fetch.inc');
include ('feedcreator.class.php');
/* Set RSS properties */
$rss = new UniversalFeedCreator();
$rss->useCached();
$rss->title = $SITE_TITLE;
$rss->description = $SITE_DESRIPTION;
$rss->link = $DOMAIN_NAME;
$rss->syndicationURL = $FEED_URL;
$rss->encoding = 'utf8';
/* Set Image properties
$image = new FeedImage();
$image->title = $SITE_TITLE . " Logo";
$image->url = $SITE_LOG_URL;
$image->link = $DOMAIN_NAME;
$image->description = "Feed provided by " . $SITE_TITLE . ". Click to visit.";
$rss->image = $image;
*/
function showSummary($url, $num = 10, $showfullfeed = false) {
global $rss, $DOMAIN_NAME, $SITE_AUTHOR, $SITE_TITLE;
$num_items = $num;
# $rss1 = fetch_rss($url);
if ($rss1) {
$items = array_slice($rss1->items, 0, $num_items);
foreach ($items as $item) {
$href = $item['link'];
$title = $item['title'];
if (!$showfullfeed) {
$desc = $item['description'];
} else {
$desc = $item['content']['encoded'];
}
// $desc .= '
//Copyright © '.$SITE_TITLE.'. All Rights Reserved.
//';
$pdate = $item['pubdate'];
$rss_item = new FeedItem();
$rss_item->title = $item['title'];
$rss_item->link = $item['link'];
$rss_item->description = $item['content']['encoded'];
$rss_item->date = $item['pubdate'];
$rss_item->source = $DOMAIN_NAME;
$rss_item->author = $SITE_AUTHOR;
$rss->addItem($rss_item);
}
} else {
echo "Error: Cannot fetch feed url - " . $url;
}
}
// Fetch all feeds
foreach($FEED_LIST as $v) showSummary($v);
// Sort items by date
function __usort($ad, $bd) {return strtotime($bd->date) - strtotime($ad->date);}
usort($rss->items, '__usort');
// Display items
$rss->saveFeed("RSS1.0", $RSS_CACHE . "/feed.xml");
How could I let the variable $artikel decide how many items are showed in the feed?

php How to increment number in a link end and automatically input sql from .txt file

php How to increment number in a link end and automatically input sql from .txt file
every page load another file link load
many .txt file continent in upload folder like this:
1.txt
2.txt
3.txt
and i try to input text from txt file into automatically
<?php
// TXT link Number
$start_file = 1;
$limit = 100;
for ($i = $start_file; $i <= 100; $i++):
$file = "upload/{$i}.txt";
endfor;
// PUT TXT FILE
// File Exists
if (file_exists($file)) {
// The "i" after the pattern delimiter indicates a case-insensitive search
if (preg_match("/CITATION:/", $current)) {
function getMatches($pattern, $subject) {
$matches = array();
if (is_array($pattern)) {
foreach ($pattern as $p) {
$m = getMatches($p, $subject);
foreach ($m as $key => $match) {
if (isset($matches[$key])) {
$matches[$key] = array_merge($matches[$key], $m[$key]);
} else {
$matches[$key] = $m[$key];
}
}
}
} else {
preg_match_all($pattern, $subject, $matches);
}
return $matches;
}
// Patterns
$patterns = array(
'#PETITIONER:(.*?)RESPONDENT:#is',
'#RESPONDENT:(.*?)DATE OF JUDGMENT:#is',
'#DATE OF JUDGMENT:(.*?)BENCH:#is',
'#BENCH:(.*?)CITATION:#is',
'#CITATION:(.*?):#is'
);
// PUT PHP SCRIPT
$file = "/upload/{$i}.txt";
// Open the file to get existing content
$current_ex = file_get_contents($file, NULL, NULL, 0, 1200);
$matches = getMatches($patterns, $current);
$current_full = file_get_contents($file);
// pubdate
$var = $matches[1]['2'];
$pj_sc_date = date("F j, Y", strtotime($var) );
$pj_sc_pubdate = date("y-m-d", strtotime($var) );
// Title
$titleString = "{$matches[1]['0']}{$matches[1]['1']} On {$pj_sc_date}";
$ucTitleString = ucwords(strtolower($titleString));
$pj_sc_title = $ucTitleString;
// Bench
$pj_sc_bench = $matches[1]['3'];
// url
$pj_sc_txt_url="http://example/upload/txt.php?filename={$i}";
// Citation
$pj_sc_citation = $matches[1]['4'];
// HTML
echo "<blockquote style='display:none'>";
print_r($matches); // result is below'
echo "</blockquote>";
echo "<div>";
echo "TITLE: ".$pj_sc_title;
echo "</div>";
echo "<div>";
echo "LINK: ".$pj_sc_txt_url;
echo "</div>";
echo "<div>";
echo "BENCH: ".$pj_sc_bench;
echo "</div>";
echo "<div>";
echo "CITATION: ".$pj_sc_citation;
echo "</div>";
echo "<time style='float: right;'>";
echo "DATE OF JUDGMENT: ".$pj_sc_date;
echo "</time>";
echo "<textarea style='width:100%; height:100%'>";
echo $current_full;
echo "</textarea>";
// DB Input
if(isset($pj_sc_title)) {
$servername = "localhost";
$username = "db";
$password = "ps";
$dbname = "db1";
// PJ mFeed
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO feed (title, link, pubdate, description, filenumber, citation, petitioner, respondent, bench, createdate, dlnote)
VALUES (:title, :link, :pubdate, :description, :filenumber, :citation, :petitioner, :respondent, :bench, :createdate, :dlnote)");
$stmt->bindParam(':title', $title);
$stmt->bindParam(':link', $link);
$stmt->bindParam(':pubdate', $pubdate);
$stmt->bindParam(':description', $description);
$stmt->bindParam(':filenumber', $filenumber);
$stmt->bindParam(':citation', $citation);
$stmt->bindParam(':petitioner', $petitioner);
$stmt->bindParam(':respondent', $respondent);
$stmt->bindParam(':bench', $bench);
$stmt->bindParam(':createdate', $createdate);
$stmt->bindParam(':dlnote', $dlnote);
// insert a row
$title = $pj_sc_title;
$link = $pj_sc_txt_url;
$pubdate = $pj_sc_pubdate;
$description = $current_full;
$filenumber = $i;
$citation = $pj_sc_citation;
$petitioner = $matches[1]['0'];
$respondent = $matches[1]['1'];
$bench = $pj_sc_bench;
$createdate = $db->now();
$dlnote = 'CITATION:';
$stmt->execute();
echo "New records created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
} else {
echo 'Title was not found.';
}
?>
I think the below code is what you need, reading all SQL text files inside folder [upload]
<?php
$start_file = 1;
$limit = 100;
for ($i = $start_file; $i <= 100; $i++):
$file = "upload/{$i}.txt";
endfor;
?>
Hope this helps.

how to add offset and limit to my php rss parser?

how to add an offset and limit to my PHP rss parser that returns the result as an object ?, here is what i have at the moment. it doesn't have any offset nor limit, how to approach this ?
class Rss
{
/*
*#access public
*#params url,int ''=default,int ''=default
*#usage input url,offset and limit,
*#returns content based onf the offset/limit input
*/
public function getFeed($url,$offset='',$limit=''){
$object = array();
$rss = simplexml_load_file($url);
foreach($rss->channel->item as $item){
$object[] = $item->title;
$object[] = $item->description;
$object[] = $item->link;
}
return $object;
}
}
Simpliest way
$limit = 10; $offset = 5;
$i=0; $taken=0;
foreach($rss->channel->item as $item){
if ($i>=$offset && $taken<$limit){
++$taken;
$object[] = $item->title;
$object[] = $item->description;
$object[] = $item->link;
}
//little optimization here
if ($taken == $limit)
break;
++$i;
}
Of course you can store $limit and $offset as object properties, or get them elsewhere.
how about a single counter thing? set offset/limit as needed
public function getFeed($url,$offset='',$limit=''){
$object = array();
$rss = simplexml_load_file($url);
$offset = 3; $limit = 8; $counter = 0;
foreach($rss->channel->item as $item){
$counter++;
if ($counter > $offset && $counter < $limit) {
$object[] = $item->title;
$object[] = $item->description;
$object[] = $item->link;
}
}
return $object;
}
You can use SimpleXMLElement::xpath. This way you don't have to traverse all items just for counting things.
public function getFeed($url, $offset = 1, $limit = -1){
$object = array();
$rss = simplexml_load_file($url);
$limitCriteria = '';
if ($limit > 0) {
$limitCriteria = 'and position() <= ' . ((int)$offset + (int)$limit + 1);
}
foreach($rss->xpath(sprintf('//item[position() >= %s %s]', (int)$offset, $limitCriteria)) as $item){
$object[] = $item->title;
$object[] = $item->description;
$object[] = $item->link;
}
return $object;
}

Categories