John Davidson

dom - Return array of all div class names from html source using php

0 comments
Message:


from a html source, using dom and xpath how would I return an array containing all the div class names? I use the following which returns all the div class names that contain "XX", but don't know the query to use for $targets to return all. I know this should be simple but I can't find one that works.


   $doc = new DOMDocument();
$doc->loadHTML($data);
$xpath = new DOMXpath($doc);
$targets = $xpath->query(".//div[contains(@class, 'XX')]");
$classNames_array = array();
foreach ($targets as $target) {
$classNames_array[] = $target->textContent;
}
print_r(array_values($classNames_array));

Thanks.



My Answer:
$html = '
Div 1
Div 2
Div 3
';
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$divs = $xpath->query('//div/@class');
$classNames = array();
foreach ($divs as $div) {
$classNames[] = $div->nodeValue;
}
print_r($classNames);
?>
This code will output:
Array
(
[0] => class1
[1] => class2
[2] => class3
)

Rate this post

3 of 5 based on 4047 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us