写入dom节点php时,大字符串被截断

时间:2015-07-11 20:06:31

标签: php xml

我使用以下代码将值写入php中的xml文件。

if(isset($_POST['title']) && isset($_POST['content'])){
    $news = new DOMDocument();
    $news->load('../files/news.xml');

    $parentNode = $news->getElementById('newsContainer');
    $newsNodes  = $news->getElementsByTagName('News');

    echo $_POST['content'];

    if($newsNodes->length > 0){
        $newsItem = $news->createElement('News');

        $newsItemTitle = $news->createElement('Title');
        $newsItemTitle->nodeValue = $_POST['title'];

        $newsItemContent = $news->createElement('Content');
        $newsItemContent->nodeValue = $_POST['content']; //The value I assign here gets cut out

        $newsItem->appendChild($newsItemTitle);
        $newsItem->appendChild($newsItemContent);
        $news->documentElement->appendChild($newsItem);

        $result = $news->save('../files/news.xml');

        if($result == FALSE){
            echo 'false';
        }else{
            echo 'true';
        }
    }else{
        $newNewsContentNode = new DOMDocument();

        $newsContainer = $newNewsContentNode->createElement('NewsContainer');
        $newsItem = $newNewsContentNode->createElement('News');

        $newsItemTitle = $newNewsContentNode->createElement('Title');
        $newsItemTitle->nodeValue = $_POST['title'];

        $newsItemContent = $newNewsContentNode->createElement('Content');
        $newsItemContent->nodeValue = $_POST['content']; //The value I assign here gets cut out

        $newsItem->appendChild($newsItemTitle);
        $newsItem->appendChild($newsItemContent);
        $newsContainer->appendChild($newsItem);

        $newNewsContentNode->appendChild($newsContainer);

        $result = $newNewsContentNode->save('../files/news.xml');

        if($result == FALSE){
            echo 'false';
        }else{
            echo 'true';
        }

    }

}

我保存了一个包含1065个字符的字符串,但是当我检查xml文件时,该节点只包含给定字符串的一部分。我查看了通过POST发出的字符串,它很好。我在这做错了什么?

1 个答案:

答案 0 :(得分:1)

不要将DOMNode::$nodeValueDOMDocument::createElement()的第二个参数用于变量值。这是一个转义bug,它可以破坏生成的XML。

$dom = new DOMDocument();
$dom->appendChild($dom->createElement("foo"));
$dom->documentElement->nodeValue = 'a & b';
echo $dom->saveXml();

输出:

Warning: main(): unterminated entity reference b in /tmp/execpad-145b170ab9f7/source-145b170ab9f7 on line 5
<?xml version="1.0"?>
<foo>a </foo>

您需要使用DOMDocument::createTextNode()来避免此问题。

$dom = new DOMDocument();
$dom->appendChild($dom->createElement("foo"));
$dom->documentElement->appendChild(
  $dom->createTextNode('a & b')
);
echo $dom->saveXml();

输出:

<?xml version="1.0"?>
<foo>a &amp; b</foo>