This section contains the detail about the Checking Attribute of xml in PHP.
PHP XML Check Attribute Example:
In this example, we can check xml element attribute using php. The getElementsByTagName("tagname") is find out the particular element in the xml file and the hasAttribute("attribute name") check the attribute and return boolean value(true or false). If hasAttribute("attribute name") return true then attribute exist or if return false then attribute not exist for the element. If attribute exist then we can use getAttribute() function to get the attribute value.
Example :
<?php $xmldoc = new DomDocument; $xmldoc->Load('root.xml'); $child1 = $xmldoc->getElementsByTagName('child1')->item(0); echo "<HTML><Head>"; echo "<title>Checking Attribute Example</title>"; echo "</Head><body><B>"; if($child1 ->hasAttribute('name')){ echo "Attribute value :".$child1->getAttribute('name'); }else{ echo "Attribute 'name' does not exist <br/>"; } if($child1 ->hasAttribute('chield1_attribute')){ echo "chield1_attribute value :".$child1->getAttribute('chield1_attribute'); }else{ echo "Attribute 'chield1_attribute' does not exist"; } echo "</B></body></HTML>"; ?>
The root.xml file is:
<?xml version="1.0"?> <root> <child1 chield1_attribute="chield1 attribute value">clied1 text</child1> <child2 >clied2 text</child2> </root>
Now you can run this example and see the output in the web browser.
Output:
Attribute 'name' does not exist
chield1_attribute value : chield1 attribute value
[ 0 ] Comments