Mark Wilson I am the creator of TopXML. I am available for international and local (Australia) contracts. I am a Solution Architect/Business Analyst. I have worked in IT in several countries (NZ, Australia, South Africa, UK) building and training teams for government and very large non-governmental organizations. I am ex-Microsoft Consulting Services. I wrote the first book on Microsoft XML published in 2000 called XML Programming with VB and ASP. Most recently I have been building tools for the SEO industry. Ask me for a 37 point SEO health-checkup for your website.
First posted :
03/24/2008
Times viewed :
379
PHP SimpleXML: Function Load_File
PHP Version: PHP 5
Description
Sometimes it is required to convert your well-formed XML
document into a simpleXML object. simplexml_load_file() converts you XML file into an object so that you
can manipulate your file as a XML object. To simplify things, an external file
is used to contain the XML strings, and read them with the simplexml_load_file() function. For example
if you want to read an XML file such as the one you created during the very
beginning of XML document creation part of this tutorial. domxml_open_file() function creates a
DOM object from XML file.
This function will convert
the well-formed XML document in the file specified by filename to an object
of class SimpleXMLElement. If any errors occur
during file access or interpretation, the function returns FALSE.
Example:
The XML file contains.
<?xml
version="1.0" encoding="UTF-8"?>
<Persons>
<Person>
<First>Test1n</First>
<Title>Mr.</Title>
<Last>Test2</Last>
<Phone>1111</Phone>
<Email>Test1@yahoo.com</Email>
</Person>
<Person>
<First>Test3</First>
<Title>Mr.</Title>
<Last>Test3</Last>
<Phone>1111</Phone>
<Email>test2@yahoo.com</Email>
</Person>
</Persons>
The PHP code is :
The above file is stored in E:/topxml/person.xml.
$default_dir = "E:/topxml/person.xml";
$Persons = simplexml_load_file($default_dir);
//var_dump($Persons);
foreach($Persons->Person as $person_key
=> $person_val){
echo
"The root element <B>Persons</B> contains an element named
<B>$person_key</B><BR>";
}
Output:
The root element Persons contains an element named Person The root element Persons
contains an element named Person
How
it Works:
$Persons = simplexml_load_file($default_dir);
The $Persons variable
contains an object that can be used much like an ordinary array. To get the
names and values from the variable, use the foreachstatement to return keys and values, just like with an ordinary array:
foreach($Persons->Person as $person_key => $person_val){
echo "The root element <B>Persons</B>
contains an element named
<B>$person_key</B><BR>";
}
In fact you can use var_dump() function to see the
content