PHP SimpleXML Get Node/Attribute Values

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.
Sample XML File (Base Example)
students.xml
Load XML File Using SimpleXML
Get Node (Element) Values
Access All Nodes Using Loop
XML elements accessed like object properties
Get Single Node Value by Index
Get Attribute Values (Very Important)
XML Attribute
PHP Code
Attributes are accessed using array syntax
Get Node + Attribute Together
Check If Node or Attribute Exists
Prevents errors in real projects
Type Casting Node Values
By default, node values are strings.
Useful for calculations
Get Attributes List
Convert Node Value to String Explicitly
Helpful in strict comparisons.
Common Mistakes
- Using
->idinstead 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
