PHP addAttribute() 函数

定义和用法

addAttribute() 函数给 SimpleXML 元素添加一个属性。

该函数无返回值。

语法

class SimpleXMLElement
{
string addAttribute(name,value,ns)
} 
参数 描述
name 必需。规定属性的名称。
value 必需。规定属性的值。
ns 可选。规定属性的命名空间。

实例

XML 文件:

<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>

PHP 代码:

<?php
$xml = simplexml_load_file("test.xml");

$xml->body[0]->addAttribute("type", "small");

foreach($xml->body[0]->attributes() as $a => $b)
  {
  echo $a,'="',$b,'"';
  }
?>

输出:

type="small"