simplexml_load_file()
SimpleXML is a PHP extension that provides a simple and easy-to-use API for working with XML documents. The SimpleXMLElement::loadFile() function is one of the
Introduction
simplexml_load_file() reads an XML file from disk (or a URL) and converts its contents into a SimpleXMLElement object that you can navigate with ordinary PHP property and array syntax. It is the file-based entry point of the SimpleXML extension — the simplest way to turn an XML document into something you can loop over and read.
Reach for it whenever you have an XML file — a config file, an RSS/Atom feed, an API response saved to disk, or a sitemap — and you want to pull values out without writing a parser by hand. If your XML lives in a string instead of a file, use its sibling simplexml_load_string() instead.
This chapter covers the function signature, a complete working example (including the XML it reads), how to access attributes and namespaces, and how to handle load failures cleanly.
Syntax
simplexml_load_file(
string $filename,
?string $class_name = SimpleXMLElement::class,
int $options = 0,
string $namespace_or_prefix = "",
bool $is_prefix = false
): SimpleXMLElement|false| Parameter | Description |
|---|---|
$filename | Path or URL of the XML file to load. |
$class_name | Class to instantiate. Must extend SimpleXMLElement; defaults to SimpleXMLElement itself. |
$options | Bitmask of libxml option constants such as LIBXML_NOCDATA or LIBXML_NOBLANKS. |
$namespace_or_prefix | Namespace prefix or URI to restrict the returned tree to. |
$is_prefix | true if the previous argument is a prefix, false if it is a URI. |
Return value: a SimpleXMLElement on success, or false if the file cannot be read or contains malformed XML.
A complete example
Assume a file named books.xml sits next to your script:
<?xml version="1.0" encoding="UTF-8"?>
<library>
<book id="b1">
<title>The PHP Way</title>
<author>Jane Doe</author>
<price currency="USD">29.99</price>
</book>
<book id="b2">
<title>XML in Practice</title>
<author>John Smith</author>
<price currency="EUR">24.50</price>
</book>
</library>Load it, confirm it parsed, and iterate over the <book> elements:
<?php
$xml = simplexml_load_file('books.xml');
if ($xml === false) {
echo "Failed to load XML file.\n";
exit(1);
}
foreach ($xml->book as $book) {
echo $book->title . " by " . $book->author . "\n";
}Output:
The PHP Way by Jane Doe
XML in Practice by John SmithNote the strict === false comparison. SimpleXML objects are "truthy", so a loose if (!$xml) check can misbehave on edge cases — always compare against false explicitly.
Reading attributes
SimpleXML exposes child elements as object properties ($book->title) and XML attributes through array-style access ($book['id']). Because the values are SimpleXMLElement objects rather than plain strings, cast them with (string) before using them in calculations or comparisons:
<?php
$xml = simplexml_load_file('books.xml');
foreach ($xml->book as $book) {
$id = (string) $book['id'];
$currency = (string) $book->price['currency'];
echo "{$id}: {$book->title} — {$book->price} {$currency}\n";
}Output:
b1: The PHP Way — 29.99 USD
b2: XML in Practice — 24.50 EURWorking with namespaces
When a document declares XML namespaces, plain property access only reaches the default namespace. Use ->children($namespaceUri) to descend into a namespaced branch and ->attributes($namespaceUri) to read namespaced attributes:
<?php
// Access elements in the Atom namespace.
$atom = $xml->children('http://www.w3.org/2005/Atom');
echo $atom->title;For a deeper look at namespaces and traversal, see SimpleXML in PHP.
Handling load failures gracefully
By default, malformed XML emits PHP warnings. To suppress those and inspect the errors yourself, turn on internal error handling with libxml_use_internal_errors() before loading:
<?php
libxml_use_internal_errors(true);
$xml = simplexml_load_file('missing.xml');
if ($xml === false) {
echo "Could not load the file:\n";
foreach (libxml_get_errors() as $error) {
echo " " . trim($error->message) . "\n";
}
libxml_clear_errors();
}Output:
Could not load the file:
failed to load external entity "missing.xml"This pattern keeps your output clean and gives you structured access to every parse error via libxml_get_errors().
Common gotchas
falsevs. warning. A missing file or a syntax error returnsfalseand raises a warning unless you enable internal errors. Always check the return value.- Cast before comparing.
$book->price == 29.99works by coincidence;(float) $book->price === 29.99is what you actually want. - Reading remote files.
$filenamemay be a URL, but that requiresallow_url_fopento be enabled inphp.ini. - Writing back. SimpleXML is great for reading. To serialize an element back to an XML string, call
asXML().
Conclusion
simplexml_load_file() is the quickest way to load an XML file into a navigable object tree in PHP. Combine it with strict === false checks, (string) casts when reading values, and libxml error handling, and you have a robust foundation for consuming feeds, configs, and XML APIs. For string input use simplexml_load_string(), and for full traversal techniques continue with SimpleXML in PHP.