2

今週は PHP を独学し、テスト プロジェクトとして、XML データを使用して短い投稿情報を保存/取得する非常に単純なマイクロブログを作成しました。この質問を参照したところ、私が望んでいたものに似た XML ドキュメントを作成することができました。

しかし、私は自分で理解できない1つの問題に遭遇しました。リンクされたソリューションでは、同じオブジェクトが何度も更新され、新しい情報は追加されません。

例、「3 番目のテスト投稿」:

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

そして「4番目のテスト投稿」:

<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');

私が望んでいるのは、複数の「投稿」要素を作成し、子を最新の要素にのみ追加することです。

ヘルプ/ヒントをいただければ幸いです。

4

2 に答える 2

1

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');
于 2013-11-01T13:34:48.357 に答える