PHP SimpleXML Get Node/Attribute Values

PHP Tutorial

📄 PHP SimpleXML – Get Node & Attribute Values

Using PHP SimpleXML, you can easily read XML node (element) values and attribute values just like accessing object properties.
This topic is very important for AJAX XML, APIs, RSS feeds, and interviews.


1️⃣ Sample XML File (Base Example)

students.xml

<?xml version="1.0" encoding="UTF-8"?>
<students>
<student id="101">
<name>Amit</name>
<marks>85</marks>
<city>Kolkata</city>
</student>
<student id="102">
<name>Ravi</name>
<marks>72</marks>
<city>Delhi</city>
</student>
</students>

2️⃣ Load XML File Using SimpleXML ⭐



3️⃣ Get Node (Element) Values ⭐

Access All Nodes Using Loop


✔ XML elements accessed like object properties


4️⃣ Get Single Node Value by Index ⭐


📌 Index starts from 0


5️⃣ Get Attribute Values ⭐ (Very Important)

XML Attribute

<student id="101">

PHP Code


✔ Attributes are accessed using array syntax


6️⃣ Get Node + Attribute Together ⭐



7️⃣ Check If Node or Attribute Exists ⭐


 

✔ Prevents errors in real projects


8️⃣ Type Casting Node Values ⭐

By default, node values are strings.

$marks = (int)$student->marks;

✔ Useful for calculations


9️⃣ Get Attributes List


 


🔟 Convert Node Value to String Explicitly

$name = (string)$student->name;

📌 Helpful in strict comparisons.


1️⃣1️⃣ Common Mistakes ❌

❌ Using ->id instead of ['id']
❌ Forgetting index [0]
❌ Not checking node existence
❌ Treating attributes like elements


📌 Interview Questions & MCQs

Q1. How to access XML node value in SimpleXML?

A) $xml[name]
B) $xml->name
C) $xml:name
D) $xml(name)

Answer: B


Q2. How to access attribute value?

A) $node->id
B) $node(id)
C) $node['id']
D) $node:id

Answer: C


Q3. Index of first XML node?

A) 1
B) 0
C) -1
D) Any

Answer: B


Q4. Node values in SimpleXML are returned as?

A) Integer
B) Array
C) Object
D) String

Answer: D


Q5. Which function loads XML file?

A) xml_load()
B) simplexml_load_file()
C) parse_xml()
D) load_xml()

Answer: B


🔥 Real-Life Use Cases

✔ Reading XML API responses
✔ AJAX XML handling
✔ RSS feed parsing
✔ Configuration files
✔ Exam & interview questions


✅ Summary

  • Nodes are accessed using object notation

  • Attributes are accessed using array syntax

  • Indexing starts from 0

  • Always check node/attribute existence

  • SimpleXML is easy & interview-friendly

You may also like...