[英]php get URL of first img src inside of specified html element
我正在嘗試找到最簡單的方法來使用PHP獲取指定元素/類中的第一張圖片的URL,並將其插入Open Graph og:image
和Twitter twitter:image
<figure class="pictures">
<img src="/pictures/1.jpg"> <!-- it would be this here -->
<img src="/pictures/2.jpg">
<img src="/pictures/3.jpg">
</figure>
<meta property="og:image" content="<?php echo $og_image; ?>"/>
還想知道我是否可以通過回顯將域設置在相對URL的前面,而不是在meta標簽中將其硬編碼在回顯的前面。
嘗試這個:
function gsb($string, $start, $end)
{
$string = " " . $string;
$ini = strpos($string, $start);
if ($ini == 0)
return "";
$ini += strlen($start);
$len = strpos($string, $end, $ini) - $ini;
return substr($string, $ini, $len);
}
$pic=gsb($string,'src="','"');
我沒有安裝PHP,因此無法實際測試此代碼。 但是,可以將其作為表達該想法的偽代碼。
<?php
echo "<figure class='pictures'>";
$URLS = array("/pictures/1.jpg","/pictures/2.jpg","/pictures/3.jpg");
for($i=0;$i<count($URLS);i++) {
echo "<img src='$URLS($i)'>";
}
echo "</figure>";
echo "<meta property='og:image' content='$URLS(0)' />";
?>
這將為您提供所需的結果,使添加/刪除img更加容易,並且如果您的代碼朝該方向擴展,則可以通過算法生成img列表。
要獲取服務器的域,請簽出$_SERVER['HTTP_HOST']
和$_SERVER['SERVER_NAME']
with javascript like this BUT
**by using php FOLLOW THIS LINK**
[http://stackoverflow.com/questions/10130858/get-img-src-with-php][1]
//this is jquery code for finding the SRC of first imahe
<script>
//$( document ).ready(function() {//here we are playing with image so use
$( window ).load(function() {
var image_url = $( ".pictures img:first-child" ).attr("src");
//in variable image_url the url of the image
alert(image_url);
});
</script>
[1]: http://stackoverflow.com/questions/10130858/get-img-src-with-php
USING PHP:-
<?php
//i just copy that code from upper link and make small change
//if you are generating these image by loop then generate $html variable and use this code
$html = '<img src="/arrow_down.png"><img src="/arrow_down1.png"><img src="/arrow_down2.png">';
$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
echo $src = $xpath->evaluate("string(//img/@src)"); # "/images/image.jpg"
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.