2014-01-18 51 views
2

我知道DOM文檔可以用來如何從html獲取src和圖片的值,並將其存儲到php變量中?

$html = '<img id="garden" value="yellow" src="/images/flowers.png" 
     alt="Image" width="100" height="100" />'; 

$doc = new DOMDocument(); 
$doc->loadHTML($html); 
$xpath = new DOMXPath($doc); 
$src = $xpath->evaluate("string(//img/@src)"); # "/images/image.jpg" 

但我如何得到img標籤src和值,而不整個標籤硬編碼到$ HTML變量?

<img id="garden" value="yellow" src="/images/flowers.png" 
     alt="Image" width="100" height="100" /> 

回答

2

這將做

<?php 
$html='<img id="garden" value="yellow" src="/images/flowers.png" 
     alt="Image" width="100" height="100" />'; 
$dom = new DOMDocument; 
$dom->loadHTML($html); 
foreach ($dom->getElementsByTagName('img') as $tag) { 

echo $tag->getAttribute('value'); // "prints" yellow 
    echo "<br>"; 
echo $tag->getAttribute('src'); // "prints" /images/flowers.png 
} 
+0

的$ HTML仍然需要整個HTML img標籤的硬編碼。是否有可能存儲到$ html整個標籤從HTML沒有實際輸入自己? – user3121403

+0

是的,只是像這樣傳遞你的html頁面。''''''''html = file_get_contents('yourhtmlpage');' –

+1

對不起,我是一個初學者。但是這真的有助於THANKS = D – user3121403

相關問題