SyntaxStudy
Sign Up
PHP SimpleXML for Parsing XML
PHP Intermediate 5 min read

SimpleXML for Parsing XML

SimpleXML

SimpleXML provides a simple way to parse XML into an object with familiar property/array access syntax. Great for reading RSS feeds and simple XML files.

Example
<?php
$xml = simplexml_load_string('<root>
  <user id="1">
    <name>Alice</name>
    <email>alice@example.com</email>
    <roles>
      <role>admin</role>
      <role>editor</role>
    </roles>
  </user>
</root>');

echo $xml->user->name;          // "Alice"
echo $xml->user["id"];          // "1" (attribute)
foreach ($xml->user->roles->role as $role) {
    echo $role . "
";           // "admin", "editor"
}

// Convert to array
$array = json_decode(json_encode($xml), true);
Pro Tip

Cast SimpleXML elements to string with (string) before using them in string contexts — they are objects, not strings.