PHP | simplexml_load_file() Function

The simplexml_load_file() function is an inbuilt function in PHP which is used to convert the well-formed XML document into the given file to an object.

Syntax:

SimpleXMLElement simplexml_load_file( string $filename, string $class_name = "SimpleXMLElement",
                                    int $options = 0, string $ns = "", bool $is_prefix = FALSE )

Parameters: This function accepts five parameters as mentioned above and described below:

  • $filename: This parameter holds the path of filename.
  • $class_name: It is optional parameter. Use of simplexml_load_file() function return the object of specified class. That class extends the SimpleXMLElement class.
  • $options: It is optional parameter and used for additional Libxml parameter.
  • $ns: This parameter holds the Namespace prefix or URI.
  • $is_prefix: This parameter is set to TRUE if ns is a prefix and FALSE if it is URI. Its default value is FALSE.

Return Value: This function returns an object of SimpleXMLElement class with properties containing the data held within the XML document, or FALSE on failure.

Below program illustrates the simplexml_load_file() function in PHP:



gfg.xml file:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?xml version="1.0"?>
<organization>
    <name>GeeksforGeeks</name>
    <address>Noida India</address>
    <contact>
        <email>abc@geeksforgeeks.org</email>
        <mobile>+91-987654321</mobile>
    </contact>
</organization>

chevron_right


Program:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Check file exist or not
if (file_exists('gfg.xml')) {
      
    // If XML file exists then
    // load the XML file
    $xml_file = simplexml_load_file('gfg.xml');
   
    // Display the content of XML file
    var_dump($xml_file);
      
} else {
      
    exit('Fail to open the file');
}
?>

chevron_right


Output:

object(SimpleXMLElement)#1 (3) { 
    ["name"]=> string(13) "GeeksforGeeks" 
    ["address"]=> string(11) "Noida India" 
    ["contact"]=> object(SimpleXMLElement)#2 (2) {
        ["email"]=> string(21) "abc@geeksforgeeks.org" 
        ["mobile"]=> string(13) "+91-987654321" 
    }
}

Reference: https://www.php.net/manual/en/function.simplexml-load-file.php




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : Akanksha_Rai

Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.