【问题标题】:getting image src in php在php中获取图像src
【发布时间】:2010-01-18 09:35:22
【问题描述】:

如何使用 php 函数从 img 标签中获取图像源。

【问题讨论】:

    标签: php image src


    【解决方案1】:

    或者,您可以使用内置的 DOM 函数(如果您使用 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
    }
    

    这使您不必使用外部类。

    【讨论】:

      【解决方案2】:

      考虑使用look at this

      我不确定这是否是解决您问题的公认方法,但请检查以下代码 sn-p 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>';
      

      【讨论】:

        【解决方案3】:

        您可以使用 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>';
        }
        

        【讨论】:

          【解决方案4】:
          $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;
          }
          

          输出

          Array
          (
              [0] => demo/banner_31.png
              [1] => demo/my_code.png
          )
          

          【讨论】:

            猜你喜欢
            • 2019-05-14
            • 2014-07-10
            • 2018-06-06
            • 1970-01-01
            • 2021-07-14
            • 1970-01-01
            • 2011-07-04
            • 1970-01-01
            • 2019-06-13
            相关资源
            最近更新 更多