What is simplexml_ load_ file function in php?

[PHP 5, PHP 7, PHP 8]

simplexml_load_file Interprets an XML file into an object

Description

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

Parameters

filename

Path to the XML file

class_name

You 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.

options

Since Libxml 2.6.0, you may also use the options parameter to specify additional Libxml parameters.

namespace_or_prefix

Namespace prefix or URI.

is_prefix

true if namespace_or_prefix is a prefix, false if it's a URI; defaults to false.

Return Values

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

Warning

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.

Errors/Exceptions

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

Examples

Example #1 Interpret an XML document

This script will display, on success:

SimpleXMLElement Object
[
  [title] => Example Title
  ...
]

At this point, you can go about using $xml->title and any other elements.

See Also

  • simplexml_load_string[] - Interprets a string of XML into an object
  • SimpleXMLElement::__construct[] - Creates a new SimpleXMLElement object
  • Dealing with XML errors
  • libxml_use_internal_errors[] - Disable libxml errors and allow user to fetch error information as needed
  • Basic SimpleXML usage
  • libxml_set_streams_context[] - Set the streams context for the next libxml document load or write

ricardo at ricardomartins dot info

10 years ago

Sometimes we have xml's with hyphens nodes, like


value

You'll need to use


instead of

wouter at code-b dot nl

15 years ago

To correctly extract a value from a CDATA just make sure you cast the SimpleXML Element to a string value by using the cast operator:

; $xml = simplexml_load_string[$xml]; // echo does the casting for you
echo $xml->channel->item->title; // but vardump [or print_r] not!
var_dump[$xml->channel->item->title]; // so cast the SimpleXML Element to 'string' solve this issue
var_dump[[string] $xml->channel->item->title];
?>

Above will output:

Tom & Jerry

object[SimpleXMLElement]#4 [0] {}

string[11] "Tom & Jerry"

sirgrayjn at gmail dot com

6 years ago

// Be carefull if you migrate or use local machine
// for test/development.

// Windows directory separators: "\" and "/"
// You may mix separators "C:\somedir\www/img/bg.jpg".

// Mixed separators path work fine in other functions
// But simplexml_load_file[] failed with mixed separators.

// Examples:
include["C:\dir\my.php"];    // work [windows]
include["C:\dir/my.php"];    // work [windows] with mixed
include["C:/dir/my.php"];    // work [windows, linux]
simplexml_load_file["C:\dir\my.php"];    // work
simplexml_load_file["C:\dir/my.php"];    // failed with mixed
simplexml_load_file["C:/dir/my.php"];    // work

neil art neilanddeb dort com

13 years ago

Because the encoding of my XML file is UTF-8 and the
encoding of my web page is iso-8859-1 I was getting strange characters such as ’ instead of a right single quote.

The solution to this turned out to be hard to find, but really easy to implement.

//uk3.php.net/manual/en/function.iconv.php

Using the iconv[] function you can convert from one encodign to another, the TRANSLIT option seems to work best for what I needed.  Here's my example:



I found the solution on this page...
//tinyurl.com/lm39xc
Hope this helps

raduispas at gmail dot com

11 years ago

if you want to check when this function fails,make sure to compare the return value with ===  instead of == :



Otherwise you may end up with FALSE all the time even if the document is ok. Hope this helps someone ;]

kannan at 99deals dot in

10 years ago

If you have some nodes which are having special characters, it would not load properly

for an instance see the nodes below
1538-7445
Sep  1 2012 12:00:00:000AM

either you have to change the : to other special characters like '-' in order to convert it properly

Correct Node
1538-7445
Sep  1 2012 12:00:00:000AM

I have wasted my precious time while debugging this. Please aware about this. ?

info at evasion dot cc

16 years ago

Suppose you have loaded a XML file into $simpleXML_obj.
The structure is like below :

SimpleXMLElement Object
[

    [node1] => SimpleXMLElement Object
        [
            [subnode1] => value1
            [subnode2] => value2
            [subnode3] => value3
        ]

    [node2] => SimpleXMLElement Object
        [
            [subnode4] => value4
            [subnode5] => value5
            [subnode6] => value6
        ]

]

When searching a specific node in the object, you may use this function :

       

So if you want to get subnode4 value you may use this function like this :



It display "value4"

Rich

6 years ago

I stumbled on this: a single element with a simple string in it becomes a string, but a single element with a *space* in it becomes an Array, with one element, the string space.

I'm sure to XML mystics this is wise and wonderful but it really confused me,  and I thought it might confuse others.



With this method someone can change the intro in content_intro.xml and ensure that the HTML is well formed and not ruin the whole site design.

fusionstream at gmail dot com

10 years ago

If you are loading many files, this may slow down your page load time.

To set a timeout, use file_get_context and then simplexml_load_string

skutter at imprecision dot net

16 years ago

So it seems SimpleXML doesn't support CDATA... I bashed together this little regex function to sort out the CDATA before trying to parse XML with the likes of simplexml_load_file / simplexml_load_string. Hope it might help somebody and would be very interested to hear of better solutions. [Other than *not* using SimpleXML of course! ;]

It looks for any elements, htmlspecialchar[]'s the encapsulated data and then strips the "" tags out.

Nanuit at ossi dot at

11 years ago

A little function very helpfull in using simplexml_load_file behind a proxy



where HTTP_PROXY is set to e.g.: tcp://proxy:8080

jamie at splooshmedia dot co dot uk

12 years ago

A wrapper around simplexml_load_file to circumvent nasty error messages when the xml server times out or gives a 500 error etc.

cryonyx at cerebrate dot ru

13 years ago

In case you have a XML file with a series of equally named elements on one level simplexml incorrectly processes them and doesn't allow to walk through the array using foreach[]. As far as I'm concerned, it is the problem caused by PHP xml_parser [see: //ru2.php.net/manual/ru/function.xml-parser-create.php#53188].

To avoid this, just use count[] and walk through the array using for[].

Example:


 
    version.shell
    1.0
 
 
      version.core
      1.0
 
 
      file.lang
      vc.lang
 
  ...

sean at aliencreations dot com

11 years ago

If you find that you are receiving 500 errors with simplexml_load_file[] but you can access the xml/rss feed manually through a browser, your script is probably being blocked by a user agent sniffer.

Add this code before your xml call to remedy this issue

php at werner dash ott dot de

15 years ago

Making SimpleXMLElement objects session save.

Besides the effect of not surviving sessions, the SimpleXMLElement object may even crash the session_start[] function when trying to re-enter the session!

To come up with a solution for this, I used a pattern as follows. The core idea is to transform the SimpleXMLElement between session calls to and from a string representation which of course is session save.

guego dot ol at ig dot com dot br

11 years ago

Analyze fully XML.

Smokey

12 years ago

for nested and same name values i'v made up this little bit for getting and displaying multiable values from google's geocode when a exact match is not found it returns all close matches in the following format[this is an abriged version of there output]


 
    New York 24, NY, USA
   
      ..................
   
   
      -73.5850086,40.7207442,0
   
 
 
    New York 27, NY, USA
   
      ...................
   
   
      -72.8987835,40.8003588,0
   
 
 
    Cedar Place School, 20 Cedar Pl, Yonkers, NY 10705, USA
   
      ..................
   
   
      -73.8966320,40.9256520,0
   
 

mark

17 years ago

If the property of an object is empty the array is not created. Here is a version object2array that transfers properly.

rex111 at bigmir dot net

6 years ago

Get all tags and their values. [recursive]

Anonymous

16 years ago

What has been found when using the script is that simplexml_load_file[] will remove any HTML formating inside the XML file, and will also only load so many layers deep. If your XML file is to deap, it will return a boolean false.

knl at bitflop dot com

13 years ago

If you need to parse the data from SimpleXML into a session variable remember to define the data as a string first.

If you don't you will get warnings of "Node no longer exists" pointing to your session_start[] function.

This will work:

What is use of 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.

What is SimpleXML in PHP?

PHP SimpleXML Introduction SimpleXML is an extension that allows us to easily manipulate and get XML data. SimpleXML provides an easy way of getting an element's name, attributes and textual content if you know the XML document's structure or layout.

HOW include XML file in PHP?

$dom2 = new DOMDocument; $dom2->load['existingFile. xml']; $dom2->documentElement->appendChild[$dom2->importNode[$fragment, true]]; This would append the fragment as the last child of the root node.

What is use of XML in PHP?

The XML functions lets you parse, but not validate, XML documents. XML is a data format for standardized structured document exchange. More information on XML can be found in our XML Tutorial. This extension uses the Expat XML parser. Expat is an event-based parser, it views an XML document as a series of events.

Chủ Đề