simplexml_load_file()

simplexml_load_file() — Interprets an XML file into an object.

Built-in function of PHP 8.5. The manual lists it as available in PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.

What it does

Convert the well-formed XML document in the given file to an object.

Signature

simplexml_load_file(string $filename, ?string $class_name = SimpleXMLElement::class, int $options = 0, string $namespace_or_prefix = "", bool $is_prefix = false): SimpleXMLElement|false

Parameters

ParameterTypeWhat it takes
$filenamestringPath to the XML file
$class_name?stringYou may use this optional parameter so that simplexml_load_file() will return an object of the specified class. That class should extend the SimpleXMLElement class.
$optionsintBitwise OR of the libxml option constants.
$namespace_or_prefixstringNamespace prefix or URI.
$is_prefixbooltrue if namespace_or_prefix is a prefix, false if it's a URI; defaults to false.

Return value

Returns an object of class SimpleXMLElement with properties containing the data held within the XML document, or false on failure. This function may return Boolean false, but may also return a non-Boolean value which evaluates to false. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function. When LIBXML_RECOVER is set in options and the input is not empty but no root element can be recovered, an uninitialized SimpleXMLElement is returned instead of false.

Example

A runnable snippet:

// The file examples/book.xml contains an XML document with a root element // and at least an element /[root]/title. if (file_exists('examples/book.xml')) { $xml = simplexml_load_file('examples/book.xml'); print_r($xml); } else { exit('Failed to open examples/book.xml.'); }

Output:

SimpleXMLElement Object ( [book] => Array ... )

Changelog

VersionChange
8.0.0A ValueError is now thrown if options does not fit in an int.

See also

simplexml_load_string(), libxml_use_internal_errors(), libxml_set_streams_context()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page simplexml_load_file() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.