Simplexml不会将子项或属性添加到xml

时间:2011-08-16 04:40:07

标签: php xml simplexml

我的xml(hashes.xml)是

<?xml version="1.0" encoding="UTF-8" ?>
<root>
    <updated></updated>
    <players>
        <playernum>1</playernum>
        <!--Demonstration of syntax, using the value 127.0.0.1 and the first second of December 22, 2012 with salt of 000 -->
        <player id="7bea7450391c9d89c65af7a46966e45066105fa4">
            <game id="1">
                <color>red</color>
            </game>
            <game id="2">
                <color>purple</color>
            </game>
        </player>
    </players>
</root>

我的php是

<?php

$hash = $_GET["hash"];

$xml = simplexml_load_file("hashes.xml");
$xml->players->addChild("player", " ");

?>

但是当我运行php时,它不会对xml文件进行任何更改。我愿意使用任何方法,即使它不是simplexml。

1 个答案:

答案 0 :(得分:0)

您的player中已有players个孩子。 我认为您需要players$xml->players->addChild("player2", " ");

的其他名称

编辑:当我测试代码时,我看到我错了

这实际上有效

$xml = '<?xml version="1.0" encoding="UTF-8" ?>
<root>
    <updated></updated>
    <players>
        <playernum>1</playernum>
        <!--Demonstration of syntax, using the value 127.0.0.1 and the first second of December 22, 2012 with salt of 000 -->
        <player id="7bea7450391c9d89c65af7a46966e45066105fa4">
            <game id="1">
                <color>red</color>
            </game>
            <game id="2">
                <color>purple</color>
            </game>
        </player>
    </players>
</root>';


$xml = simplexml_load_string($xml);
$newPlayer = $xml->players->addChild("player", " ");
$newPlayer->addAttribute("id", "12313123123");
$newGame = $newPlayer->addChild("game", "");
$newGame->addAttribute("id", "1");
$newColor = $newGame->addChild("color", "blue");
echo $xml->asXML();

结果:

<?xml version="1.0" encoding="UTF-8"?> 
<root> 
    <updated/> 
    <players> 
        <playernum>1</playernum> 
        <!--Demonstration of syntax, using the value 127.0.0.1 and the first second of December 22, 2012 with salt of 000 --> 
        <player id="7bea7450391c9d89c65af7a46966e45066105fa4"> 
            <game id="1"> 
                <color>red</color> 
            </game> 
            <game id="2"> 
                <color>purple</color> 
            </game> 
        </player> 
        <player id="12313123123">
            <game id="1">
                <color>blue</color>
            </game>
        </player>
    </players> 
</root>