PHP XML添加编辑删除

时间:2011-01-08 19:51:51

标签: php xml

我有以下XML结构,我希望有以下代码:

插入

DELETES 根据其TITLE值删除整个元素。

将发布商的值替换为其他值

<Game type="XXX">
<TITLE>XXX</TITLE>
<PUBLISHER>XXX</PUBLISHER>
</Game>

这是我的XML结构:

<?xml version="1.0" encoding ="utf-8"?>
<GameStore>
    <Game type="adventure">
        <TITLE>Assassin's Creed: Brotherhood</TITLE>
        <PUBLISHER>Ubisoft</PUBLISHER>
    </Game>

    <Game type="adventure">
        <TITLE>Batman: Arkham Asylum</TITLE>
        <PUBLISHER>Eidos</PUBLISHER>
    </Game>
</GameStore>

3 个答案:

答案 0 :(得分:3)

使用SimpleXML:

<?php
// load the XML file
$games = simplexml_load_file('games.xml');
$i = 0;
foreach ($games as $game) {
    if ($game->TITLE == 'Batman: Arkham Asylum') {
        // remove the Game element
        unset($games->Game[$i]);
    }
    $i++;
}
// save the amended file
$games->asXML('games2.xml');
?>

答案 1 :(得分:2)

您将需要使用PHP DOM类。我认为它是这样的。

加载XML文件。

$xml = new DOMDocument();
$xml->load('path/to/file.xml');

要插入。

$node = $xml->createElement('Game');
$newnode = $xml->appendChild($node);

根据标题删除。

foreach ($xml->Game as $node) {
    if ($node->TITLE->nodeValue == 'some_title') {
        $xml->removeChild($node);
    }
}

http://www.php.net/manual/en/book.dom.php

的更多信息

答案 2 :(得分:1)

您需要学习http://www.php.net/manual/fr/book.dom.php来操作xml。

有一些提示:

// Inserts
$new_node = $dom->createElement('foo', 'bar');
$gamestore_node = $xpath->query('/*')->item(0)->appendChild($new_node);
echo $dom->saveXML();

// Delete based on title
$deletable_node = $xpath->query("//Game[TITLE/text() = 'Batman: Arkham Asylum']")->item(0);
$deletable_node->parentNode->removeChild($deletable_node);
echo $dom->saveXML();

// EDIT Replace Publisher's value with another value
$editable_node = $xpath->query("//PUBLISHER[text() = 'Ubisoft']")->item(0);
$editable_node->nodeValue = 'baz';
echo $dom->saveXML();