2017-07-20 56 views
0

我试图做的和PHP中的这个jQuery函数一样(FB Open Graph不执行JS代码,所以它必须在服务器端执行):使用DOM获取特定图像的src属性PHP

<script>captureurl=jQuery('.blog-content').find('img').attr('src'); 
jQuery('head').append("<meta property='og:image' content="+captureurl+"/></meta>");</script> 

我已经看到了我能得到这样的图像属性:

<?php doc = new DOMDocument(); 
$doc->loadHTMLFile($url); 
$xpath = new DOMXpath($doc); 
$imgs = $xpath->query("//img"); 
for ($i=0; $i < $imgs->length; $i++) { 
    $img = $imgs->item($i); 
    $src = $img->getAttribute("src"); 
    // do something with $src 
} ?> 

但我怎么可以针对与.blog内容类股利第一图片src?

感谢您的帮助:)

+4

[抓取所有图像SRC从特定的div]的可能的复制(https://stackoverflow.com/questions/35646107/抓取所有图像src从特定div) –

回答

1

与以下替换$xpath->query("//img")

$imgs = $xpath->query('//img[contains(attribute::class, "blog-content")]'); //here we are querying domdocument to find img which has class .blog-content 
+0

你也应该添加一个解释。然后,OP(以及其他未来的读者)更容易使用它并在其他情况下更改它以适应其需求。 –