PHP创建XML文件无法正常生成

时间:2016-06-27 03:46:51

标签: php xml simplexml

我正在尝试将另一个元素添加到我的xml文件中。 以下是它现在生成的内容。

flipsnack>
<title>Book 1</title>
<date>6-6-2016</date>
<link>google.com</link>
<embed>this is hetml code</embed>
<order>1</order>
<show>1</show>
<flipsnack>
<title/>
<link>hotmail.com</link>
<embed>html code all the way</embed>
<order>2</order>
<postdate/>
<show>1</show>
</flipsnack>
</flipsnack>

这是我认为它应该是......

<?xml version="1.0" encoding="UTF-8"?>
<flipsnack>

    <book>
    <title>Book 1</title>
    <date>6-6-2016</date>
    <link>google.com</link>
    <embed>this is hetml code</embed>
    <order>1</order>
    <show>1</show>
    </book>

    <book>
    <title>Book 1</title>
    <date>6-6-2016</date>
    <link>google.com</link>
    <embed>this is hetml code</embed>
    <order>1</order>
    <show>1</show>
    </book>
</flipsnack>

这是我的php代码:

$title=$_POST["post"];
$date=$_POST["date"];
$link=$_POST["link"];
$html=$_POST["html"];
$order=$_POST["order"];
$show=$_POST["show"];

$xml = simplexml_load_file("db.xml");
$sxe = new SimpleXMLElement($xml->asXML());
$newItem = $sxe->addChild("flipsnack");
$newItem->addChild("title", $title);
$newItem->addChild("link", $link);
$newItem->addChild("embed", $html);
$newItem->addChild("order", $order);
$newItem->addChild("postdate", $postdate);
$newItem->addChild("show", $show);
$sxe->asXML("db.xml"); 

我不能完全理解我从现在做的事情到我想要它做什么?谁能给我一些方向?

2 个答案:

答案 0 :(得分:0)

查看代码并了解您的错误。

<?php
$title = 'Book 1';
$link = 'google.com';
$order = 1;
$postdate = 'some postdate';
$show = 'some show';
$sxe = new SimpleXMLElement ( '<flipsnack/>' );

for($i = 0; $i < 2; $i ++) {
    $newItem = $sxe->addChild ( "book" );
    $newItem->addChild ( "title", $title );
    $newItem->addChild ( "link", $link );

    $newItem->addChild ( "order", $order );
    $newItem->addChild ( "postdate", $postdate );
    $newItem->addChild ( "show", $show );

}
echo $sxe->asXML ();
?>

输出

<?xml version="1.0"?>
<flipsnack>
    <book>
        <title>Book 1</title>
        <link>google.com</link>
        <order>1</order>
        <postdate>some postdate</postdate>
        <show>some show</show>
    </book>
    <book>
        <title>Book 1</title>
        <link>google.com</link>
        <order>1</order>
        <postdate>some postdate</postdate>
        <show>some show</show>
    </book>
</flipsnack>

答案 1 :(得分:0)

这是我想要做的事情。

$title=$_POST["title"];
$date=$_POST["date"];
$link=$_POST["link"];
$html=$_POST["html"];
$order=$_POST["order"];
$show=$_POST["show"];

$xml = simplexml_load_file("db.xml");
$sxe = new SimpleXMLElement($xml->asXML());
$newItem = $sxe->addChild("book");
$newItem->addChild("title", $title);
$newItem->addChild("date", $date);
$newItem->addChild("link", $link);
$newItem->addChild("embed", $html);
$newItem->addChild("order", $order);
$newItem->addChild("show", $show);
$sxe->asXML("db.xml");