PHP-XML selectors

We all know the getElementsByTagName function. However, wouldn’t it be nice to have a standard function for selecting elements based on an attribute value? Of course it would, but first we need to think about whether we need just the first element with the specific attribute, or all of them.

In the first case, things are pretty simple. All we do is use getElementsByTagName, which returns an array of elements with that specific tag name, and then we loop through it. In case we find an element with that certain attribute, we return it. If we don’t find any elements with that attribute value, we return NULL.

Here is the function:


function getElementByAttribute(DOMDocument $dom_xml,
 $tagname, $att_name, $att_value)
{
	$items = $dom_xml->getElementsByTagName($tagname);
	foreach($items as $item)
		if($item->getAttribute($att_name) == $att_value)
			return $item;
	return NULL;
}

Ok, pretty straightforward. We need to pass the xml handler(in case there are more than one), the tag name, the attribute name, then last and most important, the attribute value. This function returns a reference to that specific item in the xml file, so we can use all the functions associated with an xml item, like setAttribute, getAttribute etc.

Now, if we need all the elements which have the same attribute value, we have to write a function which stores them in an array and then returns it. I’ll say right from the start, I’m not really sure this is the best way to go about it, since this way you won’t be able to use the item(<index>) function, but the standard way for accessing items, array_name[<index>], works. So, it shouldn’t be too much of a problem. If you guys have any better ideas, please share them, they are very welcome.

So, on with the code:


function getElementsByAttribute(DOMDocument $dom_xml,
 $tagname, $att_name, $att_value)
{
	$array = array();
	$items = $dom_xml->getElementsByTagName($tagname);
	foreach($items as $item)
		if($item->getAttribute($att_name) == $att_value)
			array_push($array, $item);
	return $array;
}

That should do nicely. Function parameters have the same meaning as above.

StumbleUpon It!

Leave a Reply

Security Code: