PHP中使用simplexml_load_string后如何获取XML的第一个节点?
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

