简单的xml添加属性

cas*_*per 3 php xml

当我使用 PHP 在 XML 中添加新元素时,如何设置属性。我的PHP代码是这样的:

 <?php
     $xml = simplexml_load_file ( 'log.xml' );

     $movies = $xml->addChild("time");
      // add attribut `value` here in tag time

     $user = $movies->addChild("user", "");
     // add attribut `id` here in tag user

     $action = $user->addChild("action","");
     // add attribut `value` here in tag action

     $action->addChild("table","customers");

     $action->addChild("table_id","1");

     echo $xml->saveXML( 'log.xml' );
 ?>
Run Code Online (Sandbox Code Playgroud)

我希望输出看起来像这样:

// log.xml
<?xml version="1.0" encoding="utf-8"?>
<log>
<time value="2013-01-10 12:20:01">
    <user id="1">
        <action value="delete">
            <table>customer</table>
            <table_id>1</table_id>
        </action>   
        <action value="insert">
            <table>customer</table>
            <data>
                <nama>budi</nama>
            </data>
        </action>
        <action value="update">
            <table>customer</table>
            <table_id>1</table_id>
            <old_data>
                <nama>andi</nama>
            </old_data>
            <new_data>
                <nama>budi</nama>
            </new_data>
        </action>
    </user>
</time>
</log>
Run Code Online (Sandbox Code Playgroud)

请帮助我..我对 xml 很陌生

Esw*_*ala 6

使用 SimpleXMLElement::addAttribute \xe2\x80\x94 向 SimpleXML 元素添加属性

\n\n

编辑:您的用例 -

\n\n
     $action = $user->addChild("action","");\n     // add attribut `value` here in tag action\n     $action->addAttribute(\'value\',\'update\'); // add this\n\n     $action->addChild("table","customers");\n\n     $action->addChild("table_id","1");\n
Run Code Online (Sandbox Code Playgroud)\n\n

最好的例子:

\n\n

http://php.net/manual/en/simplexmlelement.addattribute.php

\n\n
<?php\n\ninclude \'example.php\';\n\n$sxe = new SimpleXMLElement($xmlstr);\n$sxe->addAttribute(\'type\', \'documentary\');\n\n$movie = $sxe->addChild(\'movie\');\n$movie->addChild(\'title\', \'PHP2: More Parser Stories\');\n$movie->addChild(\'plot\', \'This is all about the people who make it work.\');\n\n$characters = $movie->addChild(\'characters\');\n$character  = $characters->addChild(\'character\');\n$character->addChild(\'name\', \'Mr. Parser\');\n$character->addChild(\'actor\', \'John Doe\');\n\n$rating = $movie->addChild(\'rating\', \'5\');\n$rating->addAttribute(\'type\', \'stars\');\n\necho $sxe->asXML();\n\n?>\n
Run Code Online (Sandbox Code Playgroud)\n\n

归功于 PHP.Net 参考页面中的第一个示例...

\n