2014-04-01 32 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