使用Php Dom创建xml文件

时间:2014-03-09 18:31:06

标签: javascript php jquery xml domparser

我目前正在使用带有此模式的php Dom创建一个xml文件

<?xml version="1.0" encoding="UTF-8"?>
<list>
  <dict>
    <Location>None</Location>
    <XOffset>0</XOffset>
    <YOffset>0</YOffset>
  </dict>
</list>

并使用此代码通过jquery读取此内容

$.post("demo.xml",{},function(xml){
    $('dict',xml).each(function(i) {
    location = $(this).find("Location").text();
        XOffset = $(this).find("XOffset").text();
        YOffset= $(this).find("XOffset").text();

    });

但我知道我想创建像那样的

的xml文件
<key>Location</key>
<string>None</string>
<key>XOffset</key>
<string>0</string>
<key>YOffset</key>
<string>0</string>

任何人都知道如何在php dom中写这个,之后我怎么能读回来

1 个答案:

答案 0 :(得分:0)

<?php

if(!file_exists("book.xml")) {
    $books = $xml->createElement("books");
     
    $newbook = $xml->createElement("book");
    $newbook->appendChild($xml->createElement("title",$_POST['title']));
    $newbook->appendChild($xml->createElement("author",$_POST['author']));
    $newbook->appendChild($xml->createElement("year",$_POST['year']));
    $newbook->appendChild($xml->createElement("pricee",$_POST['pricee']));

    $books->appendChild($newbook);
    $xml->appendChild($books);
} else {
    // load the xml file
    $xml->load("book.xml");
    $books = $xml->documentElement;

    $newbook = $xml->createElement("book");
    $newbook->appendChild($xml->createElement("title",$_POST['title']));
    $newbook->appendChild($xml->createElement("author",$_POST['author']));
    $newbook->appendChild($xml->createElement("year",$_POST['year']));
    $newbook->appendChild($xml->createElement("pricee",$_POST['pricee']));

    $books->appendChild($newbook);
}