PHP Function to Get Array of Values from HTML

Document Object Model

The function uses Document Object Model to get array of values of any 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-values-from-html.jpg

Function Definition

public static function getValueByDOM($html, $element, $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)
{
$values[] = $content->nodeValue;
}
else if ($ca == NULL)
{
$values[] = $content->nodeValue;
}
}
return $values;
}