简体   繁体   中英

php get URL of first img src inside of specified html element

I'm trying to find the simplest way using PHP to get the URL of the first image inside a specified element/class, to insert into Open Graph og:image and 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; ?>"/>

Also wondering if I can have it get the domain in front of the relative URL through the echo, instead of hardcoding it in front of the echo in the meta tags.

Try This:

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

I don't have PHP installed, so I can't actually test this code. But take it as psuedo-code that expresses the idea.

<?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)' />";
?>

This will give you your desired result, make adding/removing imgs easier, and allow you to algorithmically generate the list of imgs if your code builds out in that direction.

For getting the domain of your server, checkout $_SERVER['HTTP_HOST'] and $_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"
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM