Saving XML created with DOMDocument gives the erro

2019-07-29 04:57发布

问题:

I am trying to generate RSS from database content. Here is the relevant fragment of the code:

$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

And here is the output:

<?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>

The problem, as you see, is that that DOMDocument is not able to insert the details into the RSS and throws the error:

Warning: DOMDocument::save() [domdocument.save]: string is not in UTF-8 in C:\Inetpub\wwwroot\cron-rss.php on line 66

When I comment out the line, the code works OK but The details node is empty. When the line is un-commented, the warning is raised and the detail node is still empty. Please advice. I'll can provide additional details if necessary.

回答1:

If the text comes from database maybe the column is not in UTF-8, try iconv.



回答2:

Off the top of my head, I'd like to see the contents of the description field wrapped in <!CDATA[]]>, just in case. Instead of createTextNode, you could try the following:

$descriptionNode->appendChild($doc->createCDATASection($descriptionText));