PHP Function to Get Array of Attribute Values from HTML

Document Object Model

The function uses Document Object Model to get array of any attribute values of particular tag element from the HTML. You can also get values from specific tags that have particular attribute and value.

images/articles/php/get-array-of-attribute-values-from-html.jpg

Function Definition

public static function getAttrByDOM($html, $element, $attr, $attrchk='class', $ca=NULL)
{
$html = mb_convert_encoding($html, "HTML-ENTITIES", 'UTF-8');

$dom = new domDocument;
$dom->preserveWhiteSpace = false;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

$contents = $dom->getElementsByTagName($element); // Array of Content

foreach($contents as $content)
{
if ($ca != NULL && $content->getAttribute($attrchk) == $ca)
{
$attr_value[] = $content->getAttribute($attr);
}
else if ($ca == NULL)
{
$attr_value[] = $content->getAttribute($attr);
}
}
return $attr_value;
}