How can I get the width and height of each element’s attribute?
For instance,
$dom = new DOMDocument;
$dom->loadHTML('<div class="item" style="width:295px; height:210px; border:1px solid #000;"></div><div></div>');
foreach( $dom->getElementsByTagName('div') as $node )
{
$style = $node->getAttribute( 'style' );
var_dump($style);
}
result,
string 'width:295px; height:210px; border:1px solid #000;' (length=49)
string '' (length=0)
but these are what I am after,
- select the
divthat has the classname ofitemonly. - get
295(width) and210(height) only.
Is it possible with DOM? Or XPATH?
EDIT:
I seem to manage to select the div with the classname now,
$dom = new DOMDocument;
$dom->loadHTML('<div class="item" style="width:295px; height:210px; border:1px solid #000;"></div><div></div>');
$xpath = new DOMXpath($dom);
foreach ($xpath->query('//*[@class="item"]') as $node) {
$style = $node->getAttribute( 'style' );
var_dump($style);
}
Now this is what I am after only,
get 295 (width) and 210 (height).
If you don’t want to use a regex, you can use simple string functions to extract what you need. Here is an example, it most likely can be improved upon.
Of course, you can replace the
$widthand$heightvariables with their string literals, and remove the calls tostrlen()as they would be constant integers.Demo