简单的xml添加属性 [英] simple xml add attribute
本文介绍了简单的xml添加属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我使用 PHP 在 XML 中添加新元素时如何设置属性.我的PHP代码是这样的:
How can I set attributes when I add new elements in XML with PHP. My PHP code is like this:
<?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' );
?>
我希望输出看起来像这样:
And I want output to look like this:
// 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>
请帮助我..我对 xml 很陌生
please help me..i am very new about xml
推荐答案
Use SimpleXMLElement::addAttribute — 向 SimpleXML 元素添加属性
Use SimpleXMLElement::addAttribute — Adds an attribute to the SimpleXML element
您的用例 -
$action = $user->addChild("action","");
// add attribut `value` here in tag action
$action->addAttribute('value','update'); // add this
$action->addChild("table","customers");
$action->addChild("table_id","1");
最好的例子:
http://php.net/manual/en/simplexmlelement.addattribute.php
<?php
include 'example.php';
$sxe = new SimpleXMLElement($xmlstr);
$sxe->addAttribute('type', 'documentary');
$movie = $sxe->addChild('movie');
$movie->addChild('title', 'PHP2: More Parser Stories');
$movie->addChild('plot', 'This is all about the people who make it work.');
$characters = $movie->addChild('characters');
$character = $characters->addChild('character');
$character->addChild('name', 'Mr. Parser');
$character->addChild('actor', 'John Doe');
$rating = $movie->addChild('rating', '5');
$rating->addAttribute('type', 'stars');
echo $sxe->asXML();
?>
归功于 PHP.Net 参考页面中的第一个示例...
Credits to first example in PHP.Net ref page...
这篇关于简单的xml添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文