PHP SimpleXML

SimpleXML functions and methods reference.

Intermediate
Key PointsSimpleXML objects are not plain objects — cast to `(string)` before use.

Functions

FunctionPurpose
simplexml_load_string从字符串加载
simplexml_load_file从文件/URL 加载
simplexml_import_domDOM 节点转 SimpleXML

Methods

MethodPurpose
children取子元素(可指定命名空间)
attributes取属性
xpathXPath 查询
asXML导出 XML 字符串
getName元素名
getNamespaces所有命名空间
addChild加子元素
addAttribute加属性
PHP
<?php
$xml = '<catalog>
  <item sku="A1"><name>键盘</name><price>199</price></item>
  <item sku="A2"><name>鼠标</name><price>89</price></item>
</catalog>';

$s = simplexml_load_string($xml);

echo count($s->item), "\n";
echo $s->item[0]["sku"], "\n";
echo (string)$s->item[1]->name, "\n";

$total = 0;
foreach ($s->item as $it) {
    $total += (int)$it->price;
}
echo $total, "\n";
Output
2
A1
鼠标
288

XPath and attributes

PHP
<?php
$s = simplexml_load_string($xml);

$r = $s->xpath('//item[@sku="A2"]/name');
echo (string)$r[0], "\n";

$r = $s->xpath('//item[price > 100]/@sku');
echo implode(",", array_map("strval", $r)), "\n";

// 属性的两种访问
echo $s->item[0]["sku"], "\n";
echo $s->item[0]->attributes()["sku"], "\n";
echo $s->item[0]->attributes()->count(), "\n";
Output
鼠标
A1
A1
A1
1

Export and modify

PHP
<?php
$s = simplexml_load_string($xml);

$s->item[0]->price = "179";
$s->item[0]->addChild("stock", "50");
$s->item[1]->addAttribute("sale", "1");

$doc = dom_import_simplexml($s)->ownerDocument;
$doc->formatOutput = true;
echo $doc->saveXML();
Output
<?xml version="1.0"?>
<catalog>
  <item sku="A1">
    <name>键盘</name>
    <price>179</price>
    <stock>50</stock>
  </item>
  <item sku="A2" sale="1">
    <name>鼠标</name>
    <price>89</price>
  </item>
</catalog>
Assigning creates or overwrites a child. Deleting needs unset($s->item[0]->price), and the resulting structure can surprise you — use DOM for complex edits.

Pitfalls

  • **Missing (string)** —— you get an object and == comparisons misbehave
  • **count()** returns 1 or 0, never false
  • **Empty elements are not null** —— after casting you get ""
  • **Namespaced elements need children()** —— direct access yields empty
if ($s->maybe) is always true because it is an object, even when the element is absent. Use if ((string)$s->maybe !== "") — SimpleXML's most counter-intuitive behaviour.

Friends & Partners