PHP Conference Japan 2024

SimpleXMLElement::addChild

(PHP 5 >= 5.1.3, PHP 7, PHP 8)

SimpleXMLElement::addChild 新增子元素至 XML 節點

說明

public SimpleXMLElement::addChild(字串 $qualifiedName, ?字串 $value = null, ?字串 $namespace = null): ?SimpleXMLElement

新增一個子元素至節點,並回傳該子元素的 SimpleXMLElement。

參數

qualifiedName

要新增的子元素名稱。

value

如果指定,則為子元素的值。

命名空間

如果指定,則為子元素所屬的命名空間。

回傳值

成功時,`addChild` 方法會回傳一個 SimpleXMLElement 物件,表示添加到 XML 節點的子元素;失敗時則回傳 null

範例

注意事項:

列出的範例可能包含 `example.php`,它指的是在基本用法指南第一個範例中找到的 XML 字串。

範例 #1 將屬性和子元素添加到 SimpleXML 元素

<?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();

?>

上述範例將輸出類似以下的內容:

<?xml version="1.0" standalone="yes"?>
<movies type="documentary">
 <movie>
  <title>PHP: Behind the Parser</title>
  <characters>
   <character>
    <name>Ms. Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#xD3;r</actor>
   </character>
  </characters>
  <plot>
   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.
  </plot>
  <great-lines>
   <line>PHP solves all my web problems</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 </movie>
 <movie>
  <title>PHP2: More Parser Stories</title>
  <plot>This is all about the people who make it work.</plot>
  <characters>
   <character>
    <name>Mr. Parser</name>
    <actor>John Doe</actor>
   </character>
  </characters>
  <rating type="stars">5</rating>
 </movie>
</movies>

另請參閱

新增註釋

使用者貢獻的註釋 6 則註釋

frosty dot z at freesbee dot fr
11 年前
補充 Volker Grabsch 的評論,說明
「請注意,雖然 addChild() 會跳脫「<」和「>」,但它不會跳脫「&」。

要解決這個問題,您可以使用直接屬性賦值,例如

<?php
$xmlelement
->value = 'my value < > &';
// 結果為 <value>my value &lt; &gt; &amp;</value>
?>

而不是

<?php
$xmlelement
->addChild('value', 'my value < > &');
// 結果為 <value>my value &lt; &gt; &</value>(無效的 XML)
?>

另請參閱:http://stackoverflow.com/questions/552957 (SimpleXMLElement 在 addChild 和 addAttribute 中處理文字值的原理)

希望有幫助
alex dot feraud at gmail dot com
13 年前
這是一個具有更多 SimpleXMLElement 功能的類別

<?php
/**
*
* SimpleXMLElement 的擴充
* @author Alexandre FERAUD
*
*/
class ExSimpleXMLElement extends SimpleXMLElement
{
/**
* 在節點中新增 CDATA 文字
* @param string $cdata_text 要新增的 CDATA 值
*/
private function addCData($cdata_text)
{
$node= dom_import_simplexml($this);
$no = $node->ownerDocument;
$node->appendChild($no->createCDATASection($cdata_text));
}

/**
* 使用 CDATA 值建立子項
* @param string $name 要新增的子元素名稱。
* @param string $cdata_text 子元素的 CDATA 值。
*/
public function addChildCData($name,$cdata_text)
{
$child = $this->addChild($name);
$child->addCData($cdata_text);
}

/**
* 將 SimpleXMLElement 程式碼新增到 SimpleXMLElement 中
* @param SimpleXMLElement $append
*/
public function appendXML($append)
{
if (
$append) {
if (
strlen(trim((string) $append))==0) {
$xml = $this->addChild($append->getName());
foreach(
$append->children() as $child) {
$xml->appendXML($child);
}
} else {
$xml = $this->addChild($append->getName(), (string) $append);
}
foreach(
$append->attributes() as $n => $v) {
$xml->addAttribute($n, $v);
}
}
}
}
?>
johninen at gmail dot com
9 年前
在 Google 網站地圖的說明文件中,行動網站地圖需要一個像這樣的元素:<mobile:mobile/>

我花了一些時間才弄清楚該怎麼做,但理解之後其實很簡單。

$mobile_schema = 'http://www.google.com/schemas/sitemap-mobile/1.0';

//建立根元素
$xml_mobile = new SimpleXMLElement('
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:mobile="'.$mobile_schema.'"></urlset>
');

//新增必要的子元素
$url_mobile = $xml_b_list_mobile->addChild('url');
$url_mobile->addChild('loc', 'your-mobile-site-url');
$url_mobile->addChild('mobile:mobile', null, $mobile_schema);

要讓這個方法正常運作,必須在根節點設定 xmlns:mobile 屬性,然後在建立 mobile:mobile 子元素時,使用它作為命名空間(第三個參數),並將值設為 null。
nwarap
7 年前
想繼續討論「&」字元串接的問題。

有時候,您會想要用賦值 (=) 的方式新增子元素 (addChild)。
這個技巧可以幫助您做到這一點。

<?php
$webOrders
= new SimpleXMLElement('<?xml version="1.0"?><WebOrders></WebOrders>');
$webOrder = $webOrders->addChild('WebOrder');
$product = $webOrder->addChild('Product');
$product[0] = 'T&M';
$product->addAttribute('price', 19.99);
$product->addAttribute('qty', 2);
var_dump($webOrders->asXML());
?>

輸出結果:

<?xml version="1.0" encoding="UTF-8"?>
<WebOrders>
<WebOrder>
<Product price="19.99" qty="2">T&amp;M</Product>
</WebOrder>
</WebOrders>
Volker Grabsch
13 年前
請注意,雖然 addChild() 會將「<」和「>」進行跳脫字元處理,但它不會跳脫「&」。

因此,addChild() 不適合處理使用者自定義的輸入!

您必須在呼叫 addChild() 之前,將所有「&」取代為「&」。

或者,使用 htmlspecialchars(),它也會取代其他字元,但由於 addChild() 不會再次取代這些字元,所以不會造成任何損害。
fluxlicious at gmail dot com
1 年前
以下的類別允許您編寫 CDATA 並新增其他屬性。

<?php
class SimpleXMLElementExtended extends \SimpleXMLElement
{
public function
addChildWithCData($name, $value)
{
$child = parent::addChild($name);
$element = dom_import_simplexml($child);
$docOwner = $element->ownerDocument;
$element->appendChild($docOwner->createCDATASection($value));
return
$child;
}
}
?>

範例
<?php
$xml
= new SimpleXMLElementExtended('<xml></xml>');
$content = $xml->addChildWithCData('content', '頁面標題');
$content->addAttribute('id', 1);
$content->addAttribute('enabled', 'true');

// 輸出:
// <xml>
// <content id="1" enabled="true"><![CDATA[頁面標題]]></content>
// </xml>
?>
To Top