我知道可以使用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" />
答案 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
}