How to : Create Attribute, Get Attribute & Check whether
an Attribute Exists in XML File
Manipulating
the nodes and the elements in an XML file is easy by using PHP code. We will see
how to create an attribute for an element in an xml file and to get an attribute
from an xml file. We will also use a function to check whether an attribute exists
in an xml file.
_______________________________________________
_______________________________________________
It is easy to do
the above tasks by using the function like createAttribute, getAttributeNode,
and hasAttribute.
Creating
an Attribute
Consider
an xml file candidate.xml as given below:
To
get an attribute that is found in a node you can use the getAttribute function
as given below. Consider an XML file candidate.xml that is given below:
<?xml
version="1.0" encoding="UTF-8"?> <candidate>
<candidatename id='candid'>Robert</candidatename> <candidatecity>New
York</candidatecity> <SSN>20072007</SSN> <organization>XYZ
Corp</organization> </candidate> The code to get the attribute
in the above file is given below. After getting the attribute it is echoed in
the form an html file so that it is displayed in the browser.
<?php $xdoc
= new DomDocument; $xdoc->Load('C:/php/xml_files/candidate.xml'); $candidatename
= $xdoc->getElementsByTagName('candidatename')->item(0); $attribNode
= $candidatename->getAttributeNode('id'); echo "<HTML><Head>"; echo
"<title> Getting Attribute Example</title>"; echo "</Head><body><B>"; echo
"Attribute Name is :".$attribNode->name; echo "<BR>Attribute
Value is :".$attribNode->value; echo "</B></body></HTML>"; ?>
The
output of the above code will be as shown in the figure below:
Checking
whether an Attribute exists
You
can use the hasAttribute function to check whether an attribute exists or not.
The sample code given below illustrates that function.
Consider
the same candidate.xml file given in the above example that has an attribute 'id'
for the element 'candidatename'. We will check this file to see if it has the
attribute using the function in PHP.
<?php $xdoc
= new DomDocument; $xdoc->Load('C:/php/xml_files/candidate.xml'); $candidatename
= $xdoc->getElementsByTagName('candidatename')->item(0); echo "<HTML><Head>"; echo
"<title>Checking Attribute Example</title>"; echo "</Head><body><B>"; if($candidatename
->hasAttribute('id')){ echo "Attribute value :".$candidatename->getAttribute('id'); }else{
echo "Attribute 'id' does not exist"; } echo "</B></body></HTML>"; ?>
The
above code checks for the 'id' attribute. For this purpose we have used an 'if'
condition. If that attribute exists then you will be displayed the value of that
attribute in the browser, otherwise you will get a message stating that the attribute
does not exist in the node checked.
The
output of this code in given in the figure below:
Technology
helps engage students - how do classroom instruction and social dynamics
change when the classroom is completely dependant on modern technology?