How to : Create Element & Get Elements from XML File using PHP
XML files using PHP is very simple and there are functions available to do these
tasks. You can create elements and then get the elements using the functions in
PHP. We will see an example on how to create element and then get that element
and display it in the browser.
To create a new element in an XML file you have to use the createElement function. The name of the element to be created is passed as a parameter to this function. You can also pass the value of that element as a parameter. Although you can add the new element using the createElement function, you cannot see it in the XML file unless you use the appendChild() function to insert it in the XML document. If there is any error in creating the element the function would return FALSE.
Consider the XML file candidate.xml that is given below:
In the above file we will add a new element called candidatedesignation.
Consider the php code given below:
After running the above code you will find that a new element has been added to the XML file as given below:
If you want to add text to that element you might use the createTextNode function.
Get Elements from an XML file
To get the elements from an XML file you can use the getElementsByTagName function. This function takes the name of the element that is to be searched for in the XML file. The parameter passed is a string. This function returns all the elements with the name passed as parameter in the form of a DOMNodeList object. To return all the elements in the XML document you can use the "*" instead of a name as a parameter to the function.
Consider an XML file candidate.xml that is given below:
From the above XML file you can get the element candidatename and then gets its attribute. This is given in the sample code below:
you can use the functions available in PHP to create elements and then to get
the elements from an XML file. These codes are very simple and you can try these
on your own to get a feel on how easy it is to work with the XML files using PHP.
Copyright - © 2004 - 2018 - All Rights Reserved.