Search code examples
phpphp-5.3domdocumentdomxpathgetattribute

Get the width and height of each element's attribute via DOM or XPATH


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,

  1. select the div that has the classname of item only.
  2. get 295 (width) and 210 (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).


Solution

  • 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.

    $width = 'width:'; $height = 'height:';
    // Adding whitespace will not affect the result
    $str = '    width:   295 px; height:   210 px; border:1px solid #000;';
    
    $width_str = strstr( $str, $width);
    echo 'Width: "' . trim( substr( $width_str, strlen( $width), stripos( $width_str, 'px;') - strlen( $width))) . '"';
    
    echo "\n";
    
    $height_str = strstr( $str, $height);
    echo 'Height: "' . trim( substr( $height_str, strlen( $height), stripos( $height_str, 'px;') - strlen( $height))) . '"';
    

    Of course, you can replace the $width and $height variables with their string literals, and remove the calls to strlen() as they would be constant integers.

    Demo