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

  1. Child nodes are accessed as object properties: $node->childNode.

  2. Attributes are accessed as array elements: $node['attribute'].

  3. Nested nodes are accessed with multiple -> operators.

  4. Casting to (string) is optional but ensures string type.

  5. SimpleXML is easy and lightweight for reading and manipulating XML.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *