PHP simplexml_load_string() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
SimpleXML

Definition

In PHP, simplexml_load_string() turns a string that contains XML into a SimpleXMLElement object that you can read like a normal object.

It is the easiest way to start with SimpleXML because you do not need a file. Child elements are read as properties such as $xml->title, and attributes are read like array keys such as $xml['id']. If the XML is not well-formed, the function returns false.

Syntax

Call simplexml_load_string() with the values you need. Start with this line.

PHP
$xml = simplexml_load_string($data);
CallWhat it does
simplexml_load_string('<book><title>PHP</title></book>')Parses the XML string and returns the root element as an object.
simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA)Passes libxml options, here merging CDATA sections into normal text.
simplexml_load_string($data) === falseChecks whether the XML could not be parsed.

The object you get back stands for the root element, so you read its children directly: use $xml->title, not $xml->book->title. Text values are SimpleXMLElement objects, so cast them with (string), (int), or (float) when you need a real PHP value.

Library declarations
PHP
simplexml_load_string(string $data, ?string $class_name = SimpleXMLElement::class, int $options = 0, string $namespaceOrPrefix = "", bool $isPrefix = false): SimpleXMLElement|false

Parameters

ParameterDescription
dataRequired. A well-formed XML string.
class_nameOptional. A class that extends SimpleXMLElement. The returned object uses this class. The default is SimpleXMLElement.
optionsOptional. libxml option flags such as LIBXML_NOCDATA, combined with the | operator. The default is 0.
namespaceOrPrefixOptional. A namespace prefix or URI that the elements to read belong to. The default is an empty string.
isPrefixOptional. Set it to true when the previous argument is a prefix instead of a namespace URI. The default is false.

Return Value

Return ValueDescription
SimpleXMLElementThe root element of the XML when parsing works.
falseReturned when the string is not well-formed XML. PHP also raises warnings unless you use libxml_use_internal_errors(true).

PHP Examples

Example 1 — Read Elements and Attributes

Parse a fixed XML string, then read a child element, an attribute, and the root name.

PHP
<?php
$data = '<book id="7"><title>PHP Basics</title><year>2024</year></book>';

$xml = simplexml_load_string($data);

echo 'Root: ', $xml->getName(), PHP_EOL;
echo 'Id: ', $xml['id'], PHP_EOL;
echo 'Title: ', $xml->title, PHP_EOL;
echo 'Year plus one: ', (int) $xml->year + 1, PHP_EOL;

How It Works

  1. simplexml_load_string() parses the string and returns the root element, which is book.
  2. $xml['id'] reads the id attribute, and $xml->title reads the title child.
  3. getName() returns the name of the current element, which is book.
  4. (int) turns the year text into a number, so adding 1 gives 2025.

Example 2 — Handle Invalid XML

Broken XML returns false. Turn on internal error handling so PHP stays quiet, then check the result.

PHP
<?php
libxml_use_internal_errors(true);

$xml = simplexml_load_string('<book><title>PHP</book>');

if ($xml === false) {
    echo 'Could not parse the XML.', PHP_EOL;
    echo 'Has errors: ', var_export(count(libxml_get_errors()) > 0, true), PHP_EOL;
    libxml_clear_errors();
}

How It Works

  1. libxml_use_internal_errors(true) stores XML problems in memory instead of printing warnings.
  2. The string closes book before closing title, so the XML is not well-formed.
  3. simplexml_load_string() returns false, and the === false check catches it.
  4. libxml_get_errors() holds the stored problems, and libxml_clear_errors() clears them afterwards.

Example 3 — Read Many Items

Count repeated elements, loop over them, and add up a numeric attribute.

PHP
<?php
$data = '<shop><item price="5">Pen</item><item price="12">Book</item></shop>';

$xml = simplexml_load_string($data);
$prices = [];

echo 'Items: ', count($xml->item), PHP_EOL;
foreach ($xml->item as $item) {
    echo $item, ': ', $item['price'], PHP_EOL;
    $prices[] = (float) $item['price'];
}
echo 'Total: ', array_sum($prices), PHP_EOL;

How It Works

  1. The XML has two item elements inside the shop element.
  2. count($xml->item) returns 2 because both items share the name item.
  3. foreach goes through each item, and $item['price'] reads its price attribute.
  4. Each price is cast to float and stored, so array_sum() adds them to 17.

Frequently Asked Questions

It parses a string that contains XML and returns a SimpleXMLElement object for the root element. You can then read elements as properties and attributes as array keys.
Use array syntax on the element, for example $xml['id']. The value is a SimpleXMLElement, so cast it with (string) or (int) when you need a plain PHP value.
The string is not well-formed XML, for example a tag is not closed or there is text before the first tag. Use libxml_use_internal_errors(true) and libxml_get_errors() to see what went wrong.
Use foreach on $xml->item, or count($xml->item) to count them. You can also read one by position, such as $xml->item[0].
Call asXML() on the object. The method saveXML() does the same thing, but asXML() is the preferred name.

Next: SimpleXMLElement::xpath()

SimpleXMLElement::xpath() runs an XPath query on an XML element and returns the matching e.

SimpleXMLElement::xpath() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful