我知道可以使用 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"
但是如何从 img 标签获取 src 和值而不将整个标签硬编码到 $html 变量中?
<img id="garden" value="yellow" src="/images/flowers.png"
alt="Image" width="100" height="100" />
最佳答案
这样就可以了
<?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
}
关于php - 如何从html中获取图片的src和值,并将其存储到php变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21199474/