PHP SimpleXML – Get Node/Attribute Values
🌿 PHP SimpleXML – Get Node and Attribute Values
With SimpleXML, you can easily access child nodes and attributes of an XML document as PHP objects.
1️⃣ Accessing Child Node Values
Output:
✅ Access child nodes using object properties: $user->id, $user->name.
2️⃣ Accessing Attributes
If the XML has attributes:
You can access attributes like this:
✅ Attributes are accessed using array syntax: $user['id'].
3️⃣ Accessing Nested Nodes
✅ Nested nodes are accessed using -> notation: $user->contact->email.
4️⃣ Convert Node to String
Sometimes, you may want to explicitly convert a node to a string:
✅ Casting to (string) ensures you get the node value as a string.
5️⃣ Key Points
-
Child nodes are accessed as object properties:
$node->childNode. -
Attributes are accessed as array elements:
$node['attribute']. -
Nested nodes are accessed with multiple
->operators. -
Casting to
(string)is optional but ensures string type. -
SimpleXML is easy and lightweight for reading and manipulating XML.
