Home >Backend Development >PHP Tutorial >Simple example of reading RSS (Feed) with PHP_PHP tutorial
I have been blogging recently, but synchronization between various blogs is troublesome. Fortunately, each blog has its own RSS aggregation system, which can be used to synchronize blog calls through RSS, so I used RSS to realize blog synchronization publishing. Just study PHP to read RSS.
RSS is written in XML, which is a data storage format. There are three ways to read XML data in PHP: using XML parsing functions, DOM modules and regular expressions. The most direct way is to directly parse XML and obtain the data in XML.
The following is the parsing code:
$rssfeed = "feed.xml";
header('Content-Type:text/html;charset= UTF-8');
$buff = "";
//Open the rss address and read it
$fp = fopen($rssfeed,"r") or die("can not open $rssfeed");
while ( !feof($fp) ) {
$buff .= fgets($fp,4096);
}
//Close the file
fclose($fp);
//Create an XML parser
$parser = xml_parser_create();
//xml_parser_set_option -- Set options for the specified XML parsing
xml_parser_set_option($parser,XML_OPTION_SKIP_WHITE,1);
//xml_parse_into_struct -- Parse XML data into the array $values
xml_parse_into_struct($parser,$buff,$values,$idx);
//xml_parser_free -- Release the specified XML parser
xml_parser_free($parser);
foreach ($values as $val) {
$tag = $val["tag"];
$type = $val["type"];
$value = $val[" value"];
//Convert tags to lowercase
$tag = strtolower($tag);
if ($tag == "item" && $type == "open"){
$is_item = 1;
}else if ($tag == "item" && $type == " close") {
//Construct the output string
echo "".$title."
";
//echo $content."
";
$is_item = 0;
}
//Only read the content in the item tag
if($ is_item==1){
if ($tag == "title") {$title = $value;}
if ($tag == "link") {$link = $value;}
if ($tag == "content:encoded"){$content=$value;}
}
}
?>
The following is the effect of using this program to read the feed: