本周自学PHP,作为一个测试项目,我一直在构建一个非常简单的微博,它使用XML数据来存储/检索短文信息。我引用了这个问题,它设法让我生成了一个类似于我想要的 XML 文档。
但是,我遇到了一个我自己无法弄清楚的问题。在链接的解决方案中,同一对象会一遍又一遍地更新,而不会在其中放入任何新信息:
例如,"第三个测试帖子":
<postslist>
<post>
<name>Third Post</name>
<date>2013-11-05</date>
<time>00:00</time>
<text>There is some more post text here.</text>
</post>
</postslist>
还有"第四个测试岗位":
<postslist>
<post>
<name>Fourth Post</name>
<date>2013-11-05</date>
<time>00:00</time>
<text>There is even more post text here.</text>
</post>
</postslist>
到目前为止,我的 PHP 类似于这样:
$postname = $_POST["name"];
$postdate = $_POST["date"];
$posttime = $_POST["time"];
$posttext = $_POST["posttext"];
$postname = htmlentities($postname, ENT_COMPAT, 'UTF-8', false);
$postdate = htmlentities($postdate, ENT_COMPAT, 'UTF-8', false);
$posttime = htmlentities($posttime, ENT_COMPAT, 'UTF-8', false);
$posttext = htmlentities($posttext, ENT_COMPAT, 'UTF-8', false);
$xml = simplexml_load_file("posts.xml");
$xml->post = "";
$xml->post->addChild('name', $postname);
$xml->post->addChild('date', $postdate);
$xml->post->addChild('time', $posttime);
$xml->post->addChild('text', $posttext);
$doc = new DOMDocument('1.0');
$doc->formatOutput = true;
$doc->preserveWhiteSpace = true;
$doc->loadXML($xml->asXML(), LIBXML_NOBLANKS);
$doc->save('posts.xml');
我希望做的是创建多个"post"元素,并仅将子元素添加到最新元素中。
任何帮助/提示将不胜感激。
首先,你不应该混合使用simplexml_
和DOMDocument
函数。前者是后者的包装器(在我看来,这不是一个特别好的包装器)。如果我是你,我只会用DOMDocument
.
$doc = new DOMDocument('1.0');
$doc->formatOutput = true;
$doc->preserveWhiteSpace = true;
$doc->load('posts.xml', LIBXML_NOBLANKS); // load the posts file with DOMDocument
$newPost = $doc->createElement('post'); // create a new <post> element
$newPost->appendChild($doc->createElement('name', $postname));
$newPost->appendChild($doc->createElement('date', $postdate));
$newPost->appendChild($doc->createElement('time', $posttime));
$newPost->appendChild($doc->createElement('text', $posttext));
$document->documentElement->appendChild($newPost); // add the new <post> to the document
$doc->save('posts.xml');
您需要先打开文件以便可以对其进行编辑,否则您将一直替换整个文档而不是添加到其中。
下面是一个关于它如何与 SimpleXML 一起工作的简短示例,到目前为止,它仍然足够简单,可以完成这项工作:
$file = 'posts.xml';
$xml = simplexml_load_file($file); // load existing file
$post = $xml->addChild('post'); // add new post child
// assign values to the post object:
$post->name = $_POST["name"];
$post->date = $_POST["date"];
$post->time = $_POST["time"];
$post->text = $_POST["posttext"];
$xml->saveXML($file); //save file with changes
。并且完全兼容它的姊妹库 DOMDocument,以防您需要那里的一些功能。它们共享相同的内存对象。