实际上我想在PHP中通过图像alt从HTML代码中获取图像URL [src],但我没有选择。
<?php
$html = '
<img border="0" src="/images/image11.jpg" alt="Image11" width="100" height="100" />
<img border="0" src="/images/image22.jpg" alt="Image22" width="100" height="100" />';
$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$src = $xpath->evaluate("string(//img/@src)");
// will return /images/image.jpg
echo $src;
?>
此代码只是获得图像的src,其中包含alt =&#34; Image22&#34;。
答案 0 :(得分:0)
$html = '<img border="0" src="/images/image11.jpg" alt="Image11" width="100" height="100" /><img border="0" src="/images/image22.jpg" alt="Image22" width="100" height="100" />';
$dom = new DomDocument();
$dom->loadHTML($html);
$images = $dom->getElementsByTagName('img');
foreach ($images as $key => $image){
if ($image->hasAttributes()){
if ($image->hasAttribute("src")){
if ($image->hasAttribute("alt")){
$alt = $image->getAttribute("alt");
if ($alt == 'Image22'){
$src = $image->getAttribute("src");
echo "<br>" . $src . "<br>";
}
}
}
}
}
答案 1 :(得分:0)
<?php
$html = '
<img border="0" src="/images/image11.jpg" alt="Image11" width="100" height="100" />
<img border="0" src="/images/image22.jpg" alt="Image22" width="100" height="100" />';
$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$res = $xpath->query('//img');
foreach($res as $img) {
echo $img->getAttribute('alt');
}
?>