doulingqiu4349 2017-04-05 22:43
浏览 44
已采纳

如何获取数据属性值?

I have a url within a data-attribute and I need to get the first one:

<div class="carousel-cell">
    <img onerror="this.parentNode.removeChild(this)"; class="carousel-cell-image" data-flickity-lazyload="http://esportareinsvizzera.com/site/wp-content/uploads/8.jpg">
</div>
<div class="carousel-cell">
    <img onerror="this.parentNode.removeChild(this);" class="carousel-cell-image" data-flickity-lazyload="http://www.finanziamentiprestitimutui.com/wp-content/uploads/2014/09/esportazioni-finanziamento-credito.jpg">
</div>
<div class="carousel-cell">
    <img onerror="this.parentNode.removeChild(this);"  class="carousel-cell-image" data-flickity-lazyload="http://www.infologis.biz/wp-content/uploads/2013/09/Export.jpg">
</div>
<div class="carousel-cell">
    <img onerror="this.parentNode.removeChild(this);"  class="carousel-cell-image"  data-flickity-lazyload="http://www.cigarettespedia.com/images/2/25/Esportazione_horizontal_name_ks_20_s_green_italy.jpg">
</div>

I have been reading lots of answers like this one and this one but I am not a php guy.

I was using this to get the first img but now I need the actual data attribute value instead

<?php
      $custom_image = usp_get_meta(false, 'usp-custom-4');
      $custom_image = htmlspecialchars_decode($custom_image);
      $custom_image = nl2br($custom_image);
      $custom_image = preg_replace('/<br \/>/iU', '', $custom_image);
      preg_match('/<img.+src=[\'"](?P<src>.+?)[\'"].*>/i',$custom_image, $image);
    ?>
   <img src="<?php echo $image['src']; ?>" alt="<?php the_title(); ?>">
  • 写回答

1条回答 默认 最新

  • douyi4991 2017-04-05 23:09
    关注

    Use DOMDocument to parse the HTML, get the elements corresponding to img tags and get the data-flickity-lazyload attribute of the first img tag:

    ...
    $DOM = new DOMDocument;
    $DOM->loadHTML($custom_image);
    $items = $DOM->getElementsByTagName('img');
    
    $mySrc = $items->item(0)->getAttribute('data-flickity-lazyload');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算