2011-11-13 6 views
2

各要素の属性の幅と高さを取得するにはどうすればよいですか?例えばDOMまたはXPATHを使用して各要素の属性の幅と高さを取得する

$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); 
} 

結果、

string 'width:295px; height:210px; border:1px solid #000;' (length=49) 
string '' (length=0) 

が、これらは私が後だ何、

  1. itemのクラス名を持つdivを選択します。
  2. (幅)と210(高さ)のみを取得します。

DOMでは可能ですか?またはXPATH?

編集:私は今、クラス名を持つdiv要素を選択するために管理しているように見える

$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); 
} 

は今、これは私がした後にのみ午前何か、

295(幅)を取得および 210(高さ)。

+0

http://stackoverflow.com/questions/3448005/ xpath-and-xquery/3448050#3448050のimplementation-condition-in-conditionは、特定のクラス属性を持つdivを取得するXPathに関する部分に答えます。インラインスタイルを分割するには、通常の文字列関数またはCSSパーサが必要です。これはDOMのドメインではありません。 – Gordon

+2

http://stackoverflow.com/questions/4432334/parse-inline-css-values-with-regex regex – Gordon

+1

のsidenoteでインラインスタイルを解析してitemのclass属性を持つdivのスタイル属性を取得する方法に答えましたあなたは '//div [@ class =" item "]/@ style'を実行することもできます。これはDOMAttrを返します。 – Gordon

答えて

1

正規表現を使用したくない場合は、単純な文字列関数を使用して必要なものを抽出できます。ここに例がありますが、それはおそらく改善することができます。もちろん

$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))) . '"'; 

、あなたはそれらの文字列リテラルと$width$height変数を置き換え、そして、彼らは一定の整数になるようstrlen()への呼び出しを削除することができます。

Demo

+0

答えてくれてありがとう、ニック! :-) – laukok

1
function GetStyleValue($style, $type){ 
$value = false; 
$all = explode(';',$style); 
foreach($all as $part){ 
    $temp = explode(':', $part); 
    if(trim($temp[0]) == $type){ 
     $value = (int)trim($temp[1]); 
    }  
} 
return $value;} 

あなただけの呼び出し、widthheightまたは他のスタイル値を取得するには、この機能を使用することができます。

$width = GetStyleValue($img->getAttribute("style"), 'width');

関連する問題