PHP SimpleXML基于xml创建表单

时间:2011-10-31 16:44:40

标签: php xml simplexml

我将xml格式化为此(一个节点的示例):

<company key="Nameofcompany" enabled="true">
    <title>Nameofcompany</title>
    <phone type="domestic" href="tel:02480">02480</phone>
    <phone type="international" href="tel:+33333333">+33 33 3333</phone>
    <email href="mailto:mail@example.com" />
    <homepage href="http://www.example.com" />
    <webcompanyURL href="http://m.example.com/sbv" />
    <balanceURL href="http://m.example.com/sbv/balance" />
    <youtube href="http://www.youtube.com/account">YouTube</youtube>
    <facebook href="http://www.facebook.com/pages/Company/45454545?sk=wall" />
    <blog href="http://www.example.com/" />
    <opening-hours>
        <line>08.15 - 16.00 (Summer 08.15-15.30)</line>
    </opening-hours>
    <services>
        <phone-company type="domestic" href="tel:02480">02480</phone-bank>
        <disable-card type="domestic" href="tel:02222">02222</disable-card>
        <disable-card type="international" href="tel:+4702222">+47 02222</disable-card>
        <disable-card type="sms" href="sms:02222?text=OLALA">02222</disable-card>
        <disable-card type="email" href="mailto:02222@example.com?subject=Olala&amp;body=Phone:+">02222@example.com</disable-card>
        <disable-card type="international" href="tel:+333333333">+33 3333333</disable-card>
        <report-accident type="domestic" href="tel:02300">02300</report-accident>
        <report-accident type="international" href="tel:+33 33 33 33 33">+33 33 33 33 33</report-accident>
    </services>
</bank>

我需要创建HTML表单来编辑和创建节点并将其保存在此xml文件中。如何实现这样的功能?

1 个答案:

答案 0 :(得分:0)

我首先构建HTML表单,然后在POST操作中检索元素 - 就像将数据保存到数据库一样。

然后你需要决定如何操作XML文档 - 在PHP中有quite a few

我首选的方法是SimpleXML,但请使用您喜欢的任何内容。像这样创建你的文档:

$doc = new SimpleXMLElement('<company key="' . $key . '" enabled="true"/>');
$doc->addChild('title', $nameOfCompany);
$hours = $doc->addChild('opening-hours');
$hours->addChild('line', $lineStr);

或者如果您希望一次性创建文档,您可以将其创建为字符串,并将其提供给SimpleXMLElement的构造函数。

一旦你对SimpleXMLElement更加熟练,请记住你可以扩展它和/或用它来做各种有趣的事情,比如XPath查询。例如,here是我正在处理的内容。

希望有所帮助!