如何从html获取src和图片的值,并将其存储到php变量中?

时间:2014-01-18 03:00:31

标签: php html

我知道可以使用DOMdocument

$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"

但是如何在不将整个标记硬编码到$ html变量的情况下从img标记中获取src和值?

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

1 个答案:

答案 0 :(得分: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
}