2017-07-20 4 views
0

私はPHPで、このjQueryの機能と同じやろうとしている(それが実行する必要があるので、FBグラフを開くにはJSコードを実行しませんが、サーバー側):DOM PHPで特定の画像のsrc属性を取得します

<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-コンテンツクラスでdivの中に最初の画像srcをターゲットにすることができますか?あなたの助けのための

感謝:)

+4

可能な複製を(https://stackoverflow.com/questions/35646107/ all-images-src-from-specific-div) –

答えて

1

以下で$xpath->query("//img")を交換してください:[特定のdivからSRCのすべての画像をフェッチ]の

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

説明を追加する必要があります。そうすればOP(および他の将来の読者)がそれを使用し、他の状況で彼らのニーズに合うように変更することはより簡単です。 –

関連する問題