如何使用PHP + mySQL从XML中获取所有节点?

时间:2015-03-01 03:49:47

标签: php mysql xml rss eregi

我需要从XML获取所有节点。我尝试使用下面的PHP编码。这是工作。但我无法从xml中获取<description>和图像。

以下是来自其他网站的XML (UTF-8泰语) http://www.dailynews.co.th/rss/rss.xml

这是我的PHP代码:

$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);
}
}

我可以抓取<title><link><pubDate>并将所有内容插入mySQL。但只有<description>我无法抓住它(图像和长文本)。

我尝试从许多帮助中搜索并从W3C学校阅读。我找不到确切的答案。

请帮忙。谢谢。

1 个答案:

答案 0 :(得分:0)

使用simplexml时,需要将值转换为字符串。试试这个:

$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;
    }
}
  • 抱歉,我忘记了}。