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.
Passes libxml options, here merging CDATA sections into normal text.
simplexml_load_string($data) === false
Checks 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.
The XML has two item elements inside the shop element.
count($xml->item) returns 2 because both items share the name item.
foreach goes through each item, and $item['price'] reads its price attribute.
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.