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"