【发布时间】:2011-08-26 05:05:09
【问题描述】:
我正在尝试从数据库内容生成 RSS。下面是相关的代码片段:
$doc = new DOMDocument();
$doc->formatOutput = true;
$doc->preserveWhiteSpace = false;
if(is_file($filePath)) {
$doc->load($filePath);
}
else {
$doc->loadXML('
<rss version="2.0">
<channel>
<title></title>
<description></description>
<link></link>
</channel></rss>
');
}
.
.
.
$titleText = $row['Subject'];
$descriptionText = $row['Detail']; // this row has the problem
$linkText = sprintf('http://www.domain.com/%s', $row['URL']);
$pubDateText = date(DATE_RSS, strtotime($row['Created']));
$titleNode = $doc->createElement('title');
$descriptionNode = $doc->createElement('description');
$linkNode = $doc->createElement('link');
$pubDateNode = $doc->createElement('pubDate');
$titleNode->appendChild($doc->createTextNode($titleText));
$descriptionNode->appendChild($doc->createTextNode($descriptionText));
$linkNode->appendChild($doc->createTextNode($linkText));
$pubDateNode->appendChild($doc->createTextNode($pubDateText));
$itemNode = $doc->createElement('item');
$itemNode->appendChild($titleNode);
$itemNode->appendChild($descriptionNode);
$itemNode->appendChild($linkNode);
$itemNode->appendChild($pubDateNode);
$channelNode = $doc->getElementsByTagName('channel')->item(0);
$channelNode->appendChild($itemNode);
$doc->save($filePath); // this is where warning is raised
这是输出:
<?xml version="1.0"?>
<rss version="2.0">
<channel>
<title>ALPHA BRAVO CHARLIE</title>
<description>DELTA ECHO FOXTROT</description>
<link>http://www.xxxxxxx.yyy/</link>
<item>
<title>Title Here</title>
<description/><!-- this node has the problem -->
<link>http://www.xxxxxxx.yyy/article/12345678/</link>
<pubDate>Sun, 01 May 2011 23:18:28 +0500</pubDate>
</item>
</channel>
</rss>
如您所见,问题在于 DOMDocument 无法将详细信息插入 RSS 并引发错误:
Warning: DOMDocument::save() [domdocument.save]: string is not in UTF-8 in C:\Inetpub\wwwroot\cron-rss.php on line 66
当我注释掉该行时,代码可以正常工作,但详细信息节点为空。当该行未注释时,将引发警告并且详细节点仍为空。请指教。如有必要,我可以提供更多详细信息。
【问题讨论】:
-
你确定,$row['Detail'] 中的字符串是 UTF-8 编码的吗?
-
当您通过
utf8_encode运行描述文本时会发生什么? -
@Damien:文本来自mysql表,列有默认排序规则,类似于latin1 swedish ci。
标签: php xml utf-8 domdocument