2014-04-01 31 views
0

我試圖找到使用PHP獲取指定元素/類內第一個圖像的URL的最簡單方法,插入到Open Graph og:image和Twitter twitter:imagephp獲取指定html元素內的第一個img src的URL

<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標籤回聲前面硬編碼。

回答

-1
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" 
?> 
+0

它必須是PHP,因爲JavaScript是不與刮兼容的領域。但是,我不明白PHP示例,因爲它不顯示任何方式來定位特定的元素/類。 – Orange

+0

你想要的第一個圖像,所以使條件,你在.php文件中生成圖像 – HaRsH

+0

可能是這段代碼可以幫助你 <?php $ html =''; $ doc = new DOMDocument(); $ doc-> loadHTML($ html); $ xpath = new DOMXPath($ doc); echo $ src = $ xpath-> evaluate(「string(// img/@ src)」); #「/images/image.jpg」 ?> – HaRsH

0

試試這個:

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="','"'); 
+0

此處'$ pic'包含所需的鏈接。 –

0

我沒有安裝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)' />"; 
?> 

這會給你你想要的結果,使添加/刪除IMGS更容易,讓你的代碼在這個方向構建出你算法生成IMGS名單。

讓你的服務器,結賬$_SERVER['HTTP_HOST']$_SERVER['SERVER_NAME']

+0

我不認爲這會起作用。我仍然是一個編程初學者,但我認爲它必須是沒有任何指定URL的內容,因爲它必須適用於許多具有不同內容的頁面,但是在同一個元素/類中。僞代碼(顯然不行,lol):'<?php get_url(img.src.1(class.figure.pictures)); ?>'。它必須是能夠獲得並回顯指定元素/類中img src的第一個URL的東西,在這種情況下,它是'

' – Orange

+0

在這種情況下,您將必須處理文檔作爲一個DOM。根據我的理解,php並不瞭解HTML周圍環境,所以您必須通過PHP傳遞整個頁面,解析出您需要的東西,生成額外的代碼,然後將它放在響應中,使用echo 。這是HaRsH推薦的。 – retrohacker