dqwr32867 2013-12-19 02:35
浏览 46

php - 如何使用loadhtml从href获取img url

how to get the img url from a href url using dom loadhtml ? i try using $link->nodeValue to get the img src url but is not working

Example url source:

<a href="www.google.com"><img src="www.google.com/test.jpg" />Photo NodeValue</a>

My php code:

// -------------------------------------------------------------------------
// ----------------------- Get URLs From Source
// -------------------------------------------------------------------------
  function getVidesURL($url) {
   $web_source               = $this->getSource($url);

   if($web_source != '') {
    $Data                     = $this->Websites_Data[$this->getHost($url)];

    preg_match($Data['Index_Preg_Match'], $web_source, $Videos_Page);
    $Videos_Page              = $Videos_Page[$Data['Index_Preg_Match_Num']];

    if($Videos_Page != '') {
     $dom = new DOMDocument;
     @$dom->loadHTML($Videos_Page);

     $links = $dom->getElementsByTagName('a');

     foreach ($links as $link) {
      $Video_Status        = "";
      $Video_Error         = "";

      $Video = array(
       "URL"       => $link->getAttribute('href'),
       "Title"     => $link->getAttribute('title'),
       "MSG"       => $link->nodeValue,
      );


// Get Image URL Start
      $dom = new DOMDocument;
      @$dom->loadHTML($Video['MSG']);

      $Video_Image = $dom->getElementsByTagName('img');
      foreach ($Video_Image as $Image) {
       $Video = array(
        "IMG"       => $link->getAttribute('src'),
       );
      }


      $Videos_URLs        .= $Video['IMG'] . '<br />';
     }
// Get Image URL Stop

     return $Videos_URLs;

    }
   }
  }

The only problem of my code is i don't know how to get the img url from a href

  • 写回答

1条回答 默认 最新

  • doulangxun7769 2013-12-19 03:36
    关注

    Here is a small function that can pull out image sources from an HTML input:

    <?php
      echo PHP_EOL;
      var_dump(getImgSrcFromHTML('<a href="www.google.com"><img src="www.google.com/test.jpg" />Photo NodeValue</a><div><img src="www.google.com/test2.jpg" /></div><table><tr><td><img src="www.google.com/test3.jpg" /></td></tr></table>'));
      echo PHP_EOL;
    
     function getImgSrcFromHTML($html){
      $doc = new DOMDocument();
      $doc->loadHTML($html);
      $imagepPaths = array();
      $imageTags = $doc->getElementsByTagName('img');
      foreach ($imageTags as $tag) {
        $imagePaths[] = $tag->getAttribute('src');
      }
      if(!empty($imagePaths)) {
        return $imagePaths;
      } else {
        return false;
      }
     }
    

    Hope this helps.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?