PHP Function Reference

PHP simplexml_load_file() Function



The PHP simplexml_load_file() function converts the well-formed XML document in the given file to an object.

Syntax

simplexml_load_file(filename, class_name, options, 
                    namespace_or_prefix, is_prefix)

Parameters

filename Required. Specify path to the XML file.
class_name Optional. Specify the class of the new object. That class should extend the SimpleXMLElement class.
options Optional. Use this parameter to specify additional Libxml parameters, which affect reading of XML documents.
namespace_or_prefix Optional. Specify Namespace prefix or URI.
is_prefix Optional. true if namespace_or_prefix is a prefix, false if it is a URI. Default is false.

Return Value

Returns an object of SimpleXMLElement class with properties containing the data held within the XML document, or false on failure.

Note: This function may return Boolean false, but may also return a non-Boolean value which evaluates to false. Therefore, use === operator for testing the return value of this function.

Exceptions

Produces an E_WARNING error message for each error found in the XML data.

Note: Use libxml_use_internal_errors() to suppress all XML errors, and libxml_get_errors() to iterate over them afterwards.

Example:

Lets assume that we have a file called test.xml. This file contains following content:

<?xml version="1.0" encoding="UTF-8"?>
<userlist>
  <user>
    <username>John123</username>
    <name>John Smith</name>
    <phone>+1-8054098000</phone>
    <address>Brooklyn, New York, USA</address>
  </user>
</userlist>  

In the example below, the simplexml_load_file() function is used to convert the given XML document to a SimpleXMLElement object.

<?php
if (file_exists('test.xml')) {
  $xml = simplexml_load_file('test.xml');
 
  print_r($xml);
} else {
  exit('Failed to open test.xml.');
}
?>

The output of the above code will be:

SimpleXMLElement Object
(
    [user] => SimpleXMLElement Object
        (
            [username] => John123
            [name] => John Smith
            [phone] => +1-8054098000
            [address] => Brooklyn, New York, USA
        )
)

❮ PHP SimpleXML Reference