Search code examples
phpsimple-html-dom

How to style the Simple_HTML_DOM output


I'm getting images and their url with the following code using Simple HTML DOM Parser:

<?php
    include_once('simple_html_dom.php');
    $url = "http://www.tokyobit.com";
    $html = new simple_html_dom();
    $html->load_file($url);
    foreach($html->find('img') as $img){
        echo $img . "<br/>";
        echo $img->src . "<br/>";
    }
?>

But the output doesn't look so nice:

output
(source: netdna-cdn.com)

So how can I style the outputs in CSS like with adding a class to each image and it's src. My CSS:

.image-and-src {
    border: 2px solid #777;
} 

So how can I add that class? : image-and-src


Solution

  • foreach($html->find('img') as $img){
        echo '<div class="img-and-src">';
        echo $img . "<br/>";
        echo $img->src . "<br/>";
        echo '</div>';
    }
    

    The two lines added to the code wraps the echo'd content in a div with your class while it loops. Now you have the possibility to also wrap the text in a span, styling them both seperately.

    If you want to add the class to just the image without styling the text, you could try @Ajeet Manral's answer :)