getting image src in php

后端 未结 4 1543
野趣味
野趣味 2021-01-16 07:17

how to get image source from an img tag using php function.

相关标签:
4条回答
  • 2021-01-16 07:52

    You can use PHP Simple HTML DOM Parser (http://simplehtmldom.sourceforge.net/)

    // Create DOM from URL or file
    
    $html = file_get_html('http://www.google.com/');
    
    // Find all images 
    
    foreach($html->find('img') as $element) {
       echo $element->src.'<br>';
    }
    
    // Find all links 
    
    foreach($html->find('a') as $element) {
       echo $element->href.'<br>';
    }
    
    0 讨论(0)
  • 2021-01-16 07:54

    Consider taking a look at this.

    I'm not sure if this is an accepted method of solving your problem, but check this code snippet out:

    // Create DOM from URL or file
    $html = file_get_html('http://www.google.com/');
    
    // Find all images 
    foreach($html->find('img') as $element) 
           echo $element->src . '<br>';
    
    // Find all links 
    foreach($html->find('a') as $element) 
           echo $element->href . '<br>';
    
    0 讨论(0)
  • 2021-01-16 07:56
    $path1 = 'http://example.com/index.html';//path of the html page
    $file = file_get_contents($path1);
    $dom = new DOMDocument;
    
    @$dom->loadHTML($file);
    $links = $dom->getElementsByTagName('img');
    foreach ($links as $link)
    {    
        $re = $link->getAttribute('src');
        $a[] = $re;
    }
    

    Output:

    Array
    (
        [0] => demo/banner_31.png
        [1] => demo/my_code.png
    )
    
    0 讨论(0)
  • 2021-01-16 08:05

    Or, you can use the built-in DOM functions (if you use PHP 5+):

    $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
    }
    

    This keeps you from having to use external classes.

    0 讨论(0)
提交回复
热议问题