Parse the RSS Feeds
<?php
// Initialize (construct) the DOM object
echo "Constructing a DOM object... ";
$doc = @new DomDocument();
if ($doc === FALSE) {
echo <<<str
Failed!!!</p>
</body>
</html>
str;
$connect -> close();
exit;
} else {
echo "done!<br />\r\n";
}
// Parse the entire rss feed array
echo "Parsing RSS feeds...";
echo "<ul>\r\n";
while (($row = $feedURLs -> fetch_assoc()) !== NULL) {
$doc -> preserveWhiteSpace = true;
$url = $row['url'];
$xmldoc = $doc -> load($url);
// need an error checker/validator here
$xpath = new DOMXPath($doc);
// Select all 'item' descendants from doc root
$docItemQry = '//item';
$rssItems = $xpath -> query($docItemQry);
// parse each 'item' element for titles, links, and descriptions
foreach ($rssItems as $rssItem) {
$rssTitles = $rssItem -> getElementsByTagName('title');
$rssTitle = $connect -> real_escape_string(utf8_encode(trim($rssTitles ->
item(0) -> nodeValue)));
$rssLinks = $rssItem -> getElementsByTagName('link');
$rssLink = $connect -> real_escape_string(utf8_encode(trim($rssLinks ->
item(0) -> nodeValue)));
$rssDescs = $rssItem -> getElementsByTagName('description');
$rssDesc = $connect -> real_escape_string(utf8_encode(trim($rssDescs ->
item(0) -> nodeValue)));
// Populate items table with parsed data
$insertSQL = <<<str
INSERT INTO items (FeedID, Link, Title, Description)
VALUES ("{row['FeedID']}", "$rssLink", "$rssTitle", "$rssDesc")
str;
$insertItem = $connect -> query($insertSQL);
// Test the $insertItem query
if ($insertItem === FALSE) {
$errno = $connect -> errno;
$err = $connect -> error;
echo <<<str
<li>
<p>PHP could not add item #$i from $url</p>
<p>The MySQL Server Said:<br />
Error number: $errno<br />
Internal error: $err</p>
<p>The SQL Statement was:</p>
<p><pre><code>$insertSQL</code></pre></p>
</li>\r\n
str;
} else {
echo " <li>Added FeedID {$feedID}, item $i</li>\r\n";
}
$i++
}
}
// Clean up
$feedURLs -> close();
$connect -> close();
// Close open tags
echo <<<str
</ul>
</body>
</html>
str;
?>
References:
View the full source file