google NewsをRSSで取得してjsonで返却するPHPプログラム

2018.12.22

Logging

<?php
//$_POST["sh"]...検索キーワード 
if ($_POST["sh"]) {
	$sh = urlencode(@xss_defence($_POST["sh"]));
	$res = simplexml_load_file("https://news.google.com/news/rss/headlines/section/q/$sh/?ned=jp&hl=ja&gl=JP");
	rss($res);
}
function rss(object $obj = null):void
{
	if (isset($obj->channel->item)) {
		if ($obj->channel->item) {
			$cnt = 0;
			foreach ($obj->channel->item as $item) {
				$result[$cnt]["title"] = (string)$item->title;
				$result[$cnt]["link"] = (string)$item->link;
				$result[$cnt]["pubDate"] = (string)$item->pubDate;
				$result[$cnt]["description"] = (string)$item->description;
				$result[$cnt]["source"] = (string)$item->source;
				$cnt++;
			}
		}
	}
	echo json_encode($result);
}

function xss_defence(mixed $val):mixed
{

    if(!isset($val))return false;
    if(is_array($val)){
        foreach ($val as $key => $value) {
            # code...
            $val[$key] = strip_tags($value);
            $val[$key] = htmlentities($val[$key],ENT_QUOTES);
        }
    }else{
        $val = strip_tags($val);
        $val = htmlentities($val,ENT_QUOTES);
    }
    return $val;
}

google NewsをRSSで取得してjsonで返却するPHPプログラムです。
ご自由にご使用ください。

タグ

0, channel-, cnt, com, defence, file, foreach, function, gl, Google, gt, headlines, hl, https, if, isset, item, ja, jp, json, load, lt, ned, News, null, obj, object, php, POST, quot, res, RSS, section, sh, simplexml, urlencode, void, xss, キーワード, プログラム, 取得, 検索, 返却,