2012-01-09 59 views
4

我正在爲一個站點創建一個RSS源。UTF8生成PHP SimpleXML的錯誤RSS源

我正在使用SimpleXML創建XML結構。當我打電話XML的$> asXML();,它會引發很多的警告:

ErrorException [ Warning ]: SimpleXMLElement::asXML() [simplexmlelement.asxml]: string is not in UTF-8 

我不知道這是什麼錯誤。它讀取的數據庫表是utf8_general_ci。我嘗試在字符串上運行utf_encode,而不是修復它。

//First create the XML root 
$xml = new SimpleXMLElement('<rss version="2.0"></rss>'); 

//Create the Channel 
$channel = $xml->addChild('channel'); 

//Construct the feed parameters 
$channel->addChild('title', 'CGarchitect Feed'); 
$channel->addChild('link', Config::get('base_url')); 
$channel->addChild('description', 'CGarchitect is the leading online community for architectural visualization professionals.'); 
$channel->addChild('pubDate', date("D, d M Y H:i:s T")); 

//Get the feed items 

$nodes = <....snip... > 

foreach ($nodes as $node) 
{ 

    //Parse the title and description 
    $title = htmlentities(strip_tags($node->title)); 
    $description = htmlentities(strip_tags($node->description)); 
    $newItem = $channel->addChild('item'); 
    $newItem->addChild('title', $title); 
    $newItem->addChild('description', $description); 
    $newItem->addChild('pubDate', date("D, d M Y H:i:s T", $node->published_at)); 

} 

header('Content-Type: application/xhtml+xml'); 
echo $xml->asXML(); 

在此先感謝...

倫納德

+0

您是否已將[MySql連接編碼](http://dev.mysql.com/doc/refman/5.5/en/charset-connection.html)設置爲UTF8爲好? – Jon 2012-01-09 23:47:20

+0

@Jon是的。 mysql_client_encoding()返回'utf8' – 2012-01-09 23:52:43

+0

您確定您正在使用UTF-8連接到數據庫嗎?在建立連接後第一次執行此查詢:mysql_query(「SET NAMES'utf8'」); – 2012-01-09 23:54:52

回答

2

我能夠重現你的問題更換您的$節點......與

class myNode { 

    public $title="(╯°□°)╯︵ ┻━┻"; 
    public $description="dscr"; 
    public $published_at=0; 

    public function __construct(){ 
     $this->published_at=time(); 
    } 

} 

$nodes = array(new myNode()); 

只需移除的通話片斷htmlentities似乎工作正常。 (輸出正確轉義爲字符實體)

+0

好的這個作品。我正在運行htmlentities,因爲我在數據庫中有一些條目,並且沒有它的字符是& .... – 2012-01-10 00:22:04

+1

或者,您可以指定字符集,如 htmlentities(strip_tags($ node-> title),ENT_COMPAT, 'UTF-8');這對我也有效 – atxdba 2012-01-10 00:49:46

+0

謝謝。爲了記錄,當我不斷收到實體'lsquo'未定義時,我無法使用htmlentities來處理它。我切換到使用htmlspecialchars和它的工作... – 2012-01-10 12:01:33