You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP中使用simplexml_load_string后如何获取XML的第一个节点?

How to Access the Root Node and Its Content with SimpleXML in PHP

When you parse your XML using simplexml_load_string, the returned object directly represents the root <Cancellation> node (the first node in your XML). Here's how to work with it:

1. Get the Root Node's Name

If you need to confirm the name of the first (root) node, use the getName() method:

$xml = simplexml_load_string($yourXmlString);
$rootNodeName = $xml->getName(); // Returns "Cancellation"
echo $rootNodeName;

2. Access the Root Node's Content (Child Elements)

Since the root node contains child elements like <version> and <customerID, you can access their text values directly using object property syntax. It’s best to explicitly cast to string to avoid unexpected behavior:

// Get the value of the <version> element
$version = (string)$xml->version;
echo $version; // Outputs "message-version"

// Get the <customerID> value
$customerId = (string)$xml->customerID;

3. Iterate Over All Child Elements of the Root

If you want to loop through all content inside the root node:

foreach ($xml->children() as $childNode) {
    $nodeName = $childNode->getName();
    $nodeValue = (string)$childNode;
    echo "Node: $nodeName, Value: $nodeValue\n";
}

4. Get the First Child Node of the Root

If you meant the first child element inside <Cancellation> (which is <version>), you can grab it like this:

$firstChild = $xml->children()[0];
$firstChildName = $firstChild->getName(); // "version"
$firstChildValue = (string)$firstChild; // "message-version"

A quick reminder: SimpleXMLElement objects are "magic"—when you use them in string contexts, they auto-convert to their text content, but explicit casting to string makes your code clearer and avoids edge cases.

内容的提问来源于stack exchange,提问作者IgorAlves

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:49:56