rob.m
rob.m

Reputation: 10571

How to get data attribute value?

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(); ?>">

Upvotes: 0

Views: 6715

Answers (1)

gmc
gmc

Reputation: 3990

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');

Upvotes: 4

Related Questions