PHP SimpleXML - Get
Retrieving data from XML using SimpleXML methods
🔍 Getting XML Data
SimpleXML provides multiple methods to retrieve data from XML documents. You can get element values, attributes, child nodes, and use XPath queries to extract specific information efficiently.
<?php
$xml = simplexml_load_file("data.xml");
$value = $xml->element; // Get element value
?>
Get Methods
Element Values
Get text content of elements
$xml->title
Attributes
Retrieve element attributes
$xml->book['id']
Child Elements
Access nested elements
$xml->children()
XPath Query
Search with XPath expressions
$xml->xpath('//item')
🔹 Getting Element Values
The simplest way to get data is accessing elements directly as object properties. Cast to string for clean output:
<?php
$xmlString = '<?xml version="1.0"?>
<company>
<name>Tech Solutions Inc</name>
<founded>2020</founded>
<employees>150</employees>
<location>
<city>San Francisco</city>
<country>USA</country>
</location>
</company>';
$xml = simplexml_load_string($xmlString);
// Get simple values
echo "Company: " . $xml->name . "<br>";
echo "Founded: " . $xml->founded . "<br>";
echo "Employees: " . $xml->employees . "<br>";
// Get nested values
echo "City: " . $xml->location->city . "<br>";
echo "Country: " . $xml->location->country;
?>
Output:
Company: Tech Solutions Inc
Founded: 2020
Employees: 150
City: San Francisco
Country: USA
🔹 Getting Attributes
Use array notation to retrieve attribute values. You can also use the attributes() method to get all attributes:
<?php
$xmlString = '<?xml version="1.0"?>
<products>
<item id="A101" stock="50" featured="true">
<name>Laptop</name>
<price currency="USD">999.99</price>
</item>
</products>';
$xml = simplexml_load_string($xmlString);
// Get specific attributes
echo "Product ID: " . $xml->item['id'] . "<br>";
echo "Stock: " . $xml->item['stock'] . "<br>";
echo "Featured: " . $xml->item['featured'] . "<br><br>";
// Get all attributes
echo "All attributes:<br>";
foreach($xml->item->attributes() as $key => $value) {
echo "$key: $value<br>";
}
// Get price attribute
echo "<br>Price: " . $xml->item->price . " ";
echo $xml->item->price['currency'];
?>
Output:
Product ID: A101
Stock: 50
Featured: true
All attributes:
id: A101
stock: 50
featured: true
Price: 999.99 USD
🔹 Getting Child Elements
Use the children() method to iterate through all child elements or access specific children:
<?php
$xmlString = '<?xml version="1.0"?>
<team>
<member role="manager">
<name>Alice Johnson</name>
<email>[email protected]</email>
</member>
<member role="developer">
<name>Bob Smith</name>
<email>[email protected]</email>
</member>
<member role="designer">
<name>Carol White</name>
<email>[email protected]</email>
</member>
</team>';
$xml = simplexml_load_string($xmlString);
// Get all child elements
echo "Team Members:<br><br>";
foreach($xml->children() as $member) {
echo "Role: " . $member['role'] . "<br>";
echo "Name: " . $member->name . "<br>";
echo "Email: " . $member->email . "<br><br>";
}
?>
Output:
Team Members:
Role: manager
Name: Alice Johnson
Email: [email protected]
Role: developer
Name: Bob Smith
Email: [email protected]
Role: designer
Name: Carol White
Email: [email protected]
🔹 Using XPath to Get Data
XPath provides powerful querying capabilities to find and extract specific data from complex XML structures:
<?php
$xmlString = '<?xml version="1.0"?>
<store>
<book category="fiction" lang="en">
<title>The Great Story</title>
<price>12.99</price>
</book>
<book category="programming" lang="en">
<title>PHP Mastery</title>
<price>45.99</price>
</book>
<book category="programming" lang="en">
<title>Web Development</title>
<price>38.50</price>
</book>
</store>';
$xml = simplexml_load_string($xmlString);
// Get all programming books
$programmingBooks = $xml->xpath('//book[@category="programming"]');
echo "Programming Books:<br>";
foreach($programmingBooks as $book) {
echo "- " . $book->title . " ($" . $book->price . ")<br>";
}
// Get books under $40
echo "<br>Books under $40:<br>";
$cheapBooks = $xml->xpath('//book[price < 40]/title');
foreach($cheapBooks as $title) {
echo "- " . $title . "<br>";
}
// Get first book title
$firstTitle = $xml->xpath('//book[1]/title');
echo "<br>First book: " . $firstTitle[0];
?>
Output:
Programming Books:
- PHP Mastery ($45.99)
- Web Development ($38.50)
Books under $40:
- The Great Story
- Web Development
First book: The Great Story
🔹 Getting Element Count
Use count() to determine how many elements exist at a specific level:
<?php
$xmlString = '<?xml version="1.0"?>
<playlist>
<song>Song One</song>
<song>Song Two</song>
<song>Song Three</song>
<song>Song Four</song>
<song>Song Five</song>
</playlist>';
$xml = simplexml_load_string($xmlString);
// Count elements
$songCount = count($xml->song);
echo "Total songs: " . $songCount . "<br><br>";
// List all songs
echo "Playlist:<br>";
$index = 1;
foreach($xml->song as $song) {
echo "$index. " . $song . "<br>";
$index++;
}
?>
Output:
Total songs: 5
Playlist:
1. Song One
2. Song Two
3. Song Three
4. Song Four
5. Song Five
🔹 Getting Element Name
Use getName() to retrieve the name of an element, useful when iterating through unknown structures:
<?php
$xmlString = '<?xml version="1.0"?>
<person>
<firstname>John</firstname>
<lastname>Doe</lastname>
<age>30</age>
<city>New York</city>
</person>';
$xml = simplexml_load_string($xmlString);
// Get element names and values
echo "Person Information:<br>";
foreach($xml->children() as $child) {
$elementName = $child->getName();
$elementValue = (string)$child;
echo ucfirst($elementName) . ": " . $elementValue . "<br>";
}
?>
Output:
Person Information:
Firstname: John
Lastname: Doe
Age: 30
City: New York
🔹 Practical Tips
💡 Best Practices for Getting Data:
- Type casting: Use (string) to convert SimpleXML objects to strings
- Check existence: Use isset() before accessing elements
- XPath efficiency: XPath is faster for complex queries
- Attribute access: Always use array notation for attributes
- Iteration: Use foreach for multiple elements with same name