PHP SimpleXML Parser

PHP Tutorial

📄 PHP SimpleXML Parser

SimpleXML is a PHP extension that allows you to read, parse, and manipulate XML data easily.
It converts XML into an object, making XML handling simple and beginner-friendly.

👉 Very common in AJAX XML, APIs, configuration files, and interviews.


1️⃣ What is SimpleXML?

  • Built-in PHP extension

  • Parses XML documents

  • Treats XML elements as objects & properties

  • Easier than DOM & SAX

📌 Best for small to medium XML files


2️⃣ Why Use SimpleXML?

✔ Easy syntax
✔ Object-based access
✔ Less code
✔ Ideal for beginners

❌ Not suitable for very large XML files


3️⃣ Sample XML File

students.xml

<?xml version="1.0" encoding="UTF-8"?>
<students>
<student>
<id>1</id>
<name>Amit</name>
<marks>85</marks>
</student>
<student>
<id>2</id>
<name>Ravi</name>
<marks>72</marks>
</student>
</students>

4️⃣ Load XML File Using simplexml_load_file()


 

✔ XML elements accessed like object properties


5️⃣ Load XML String Using simplexml_load_string()


 


6️⃣ Access Single XML Element

echo $xml->student[0]->name;

✔ Access by index


7️⃣ Read XML Attributes ⭐

XML with Attribute

<student id="101">
<name>Amit</name>
</student>

PHP Code

echo $student['id'];

8️⃣ Check XML Load Errors (Best Practice) ⭐


 


9️⃣ Convert SimpleXML Object to Array ⭐

$array = json_decode(json_encode($xml), true);
print_r($array);

✔ Useful when working with arrays


🔟 SimpleXML vs DOM ⭐ (Interview Favorite)

Feature SimpleXML DOM
Ease of use ⭐⭐⭐⭐⭐ ⭐⭐
Performance Medium High
Large XML ❌ No ✔ Yes
Beginner-friendly ✔ Yes ❌ No

1️⃣1️⃣ Common Mistakes ❌

❌ Forgetting XML file path
❌ Not checking load errors
❌ Using SimpleXML for huge XML
❌ Confusing elements & attributes


📌 Interview Questions & MCQs

Q1. What does SimpleXML do?

A) Create database
B) Parse XML
C) Send email
D) Upload file

Answer: B


Q2. Which function loads XML file?

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

Answer: C


Q3. SimpleXML converts XML into?

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

Answer: B


Q4. Which is better for large XML?

A) SimpleXML
B) DOM

Answer: B


Q5. Can SimpleXML read attributes?

A) Yes
B) No

Answer: A


🔥 Real-Life Use Cases

✔ AJAX with XML
✔ API responses (XML)
✔ RSS feeds
✔ Configuration files
✔ Exam & interview questions


✅ Summary

  • SimpleXML is the easiest way to parse XML in PHP

  • XML is accessed as objects

  • Ideal for small/medium XML files

  • Supports elements & attributes

  • Important for PHP exams & interviews

You may also like...