Introduction to PHP SimpleXML
SimpleXML is an extension of PHP. This extension has a set of functions that are used to handle the XML and to convert them in to an object. After the conversion to an object it is easy to process the XML as we do with other conventional objects. You can use the array iterators and property selectors to process that XML. If you have installed PHP5 in your system then SimpleXML is automatically turned on.
Some of the common operations that you perform with an XML document are made easy with the use of the SimpleXML functions. For example you can convert a string to create an XML document and also display it. Once the XML document is made an object using SimpleXML the elements, data, and the attributes are easily accessible with the usual operations that you do in other objects of PHP. This is one of the greatest advantages of using SimpleXML.
The functions that are available in SimpleXML include the following:
The function simplexml_load_file takes the file path as a parameter. This function would convert the file in the path into an object if the contents of the file are well-formed XML. An example of the usage of this function is,
$oFile = simplexml_load_file("C:/php/candidate.xml");
The path of the filename can be stored in a variable and that variable can also be used in the function.
During the course of a program you might have some requirement where you need to convert a well-formed XML string in to an XML object. Under such circumstances you can use the simplexml_load_string function which does that job easily for you.
$strxml = <<<XML
A code snippet that uses the function simplexml_load_string is given above.
In the above code if you want to return the well-formed xml string from the object $oxml, you can use the function simplexml_element->asXML. An example of the code snippet for this function is given below:
$oxml = simplexml_load_string($strxml);
The function simplexml_element->attributes is used to get the attributes and its values from an XML string that is well-formed.
The function simplexml_element->children is used to get the child element of an element in an XML document.
The function simplexml_element->xpath is used to perform simpleXML node xpath queries.
The simplexml_import_dom is used to convert a DOM document's node in to a simple xml node.
Apart from the above functions there are many other functions like save, loadXML, etc. You can refer to the documentation for the different types of functions available. The save is called to save an XML document that has been built from the scratch. Look at the code given below,
In this code the save function is called to save the xml document in the filename candidate2.xml. This function returns the number of bytes that were written in the document. Thus it is easy to use SimpleXML functions to handle the XML files easily.
“Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”Copyright - © 2004 - 2019 - All Rights Reserved.