Search code examples
phpmysqlxmlrsseregi

How can I grab all nodes from XML with PHP+mySQL?


I need to grab all nodes from XML. After I try use below PHP coding. It is work. But I can not grab <description> and image from xml.

Here is XML from others website (UTF-8 Thai Language) http://www.dailynews.co.th/rss/rss.xml

Here is my PHP code :

$Rsssurl_SQL="SELECT * from rss_feed_url"; 
$Rsssurl_RESULT=mysql_db_query($dbname,$Rsssurl_SQL);
while ($Rsssurl_ROW=mysql_fetch_array($Rsssurl_RESULT)) {
$request_url = $Rsssurl_ROW[1];
$xml = simplexml_load_file($request_url) or die("");
foreach($xml->channel->item as $item){
$title = $item->title;   
$content = $item->description;
$date = $item->pubDate;   
$link = $item->link;

/* I use ereg_replace to replace special characters */

$content=ereg_replace("&lt;","<",$content);
$content=ereg_replace("&gt;",">",$content);
$content=ereg_replace("&amp;","&",$content);
$content=ereg_replace("&quot;","\"",$content);
$content=ereg_replace("&#039;","\'",$content);

$title=ereg_replace("&lt;","<",$title);
$title=ereg_replace("&gt;",">",$title);
$title=ereg_replace("&amp;","&",$title);
$title=ereg_replace("&quot;","\"",$title);
$title=ereg_replace("&#039;","\'",$title);
$title=ereg_replace("\'","",$title);
$title=ereg_replace("<","", $title);
$title=ereg_replace(">","", $title);
$title=ereg_replace("&","", $title);
$title=ereg_replace("\"","", $title);
}
}

I can grab <title>, <link> , <pubDate> and insert all to mySQL. But only <description> I can not grab it all (image and long text).

I try to search from many helps and read from W3C school. I can not found exactly answers.

Please , helps. Thanks.


Solution

  • You need to cast the value as a string when using simplexml. Try this :

    $Rsssurl_SQL="SELECT * from rss_feed_url"; 
    $Rsssurl_RESULT=mysql_db_query($dbname,$Rsssurl_SQL);
    while ($Rsssurl_ROW=mysql_fetch_array($Rsssurl_RESULT)) {
        $request_url = $Rsssurl_ROW[1];
        $xml = simplexml_load_file($request_url) or die("");
        foreach($xml->channel->item as $item){
            $title = (string) $item->title;   
            $content = (string) $item->description;
            $date = (string) $item->pubDate;   
            $link = (string) $item->link;
        }
    }
    
    • Sorry , I forget } at the end.