如何获取数据属性值?

时间:2017-04-05 22:43:52

标签: php

我在数据属性中有一个url,我需要得到第一个:

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

我一直在阅读许多答案,例如this onethis one,但我不是一个php人。

我使用它来获取第一个img,但现在我需要实际的数据属性值

<?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 个答案:

答案 0 :(得分:3)

使用DOMDocument解析HTML,获取与img代码对应的元素,并获取第一个data-flickity-lazyload代码的img属性:

...
$DOM = new DOMDocument;
$DOM->loadHTML($custom_image);
$items = $DOM->getElementsByTagName('img');

$mySrc = $items->item(0)->getAttribute('data-flickity-lazyload');