June 4, 2012

PHP get element using a known attribute

Question by Ilya Karnaukhov

So lets say I have:

<?php
    $template = '<img src="{image}" editable="all image_all" />';
    $template .= '<div>';
    $template .= '<img src="{image}" editable="yes" />';
    $template .= '</div>';
?>

Now what I would like is to make the script go through all the elements containing the {image} src and checking to see if any of them have the

editable="all" 

attribute.

If so: get the second editable attribute e.g.

image_all

And include that into the src.

Answer by Starx

This task can be simplified with the use of a library suggested on comments, Simple HTML DOM Parser:

It is as easy as this:

$images = array(); //an array for your images with {image} in src
$html = "...";
foreach($html->find('img') as $element)
    if($element->src == '{image}') {
        //add to the collection
        $images[] = $element;
    }
    //Also you can compare for the editable attribute same way as above.
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!