2

Possible Duplicate:
How can I only get the alt attribute of the a p tag in PHP?

I have a the following HTML code:

<img src="test.png" alt="test1" />
<img src="test2.png" alt="test2" />

How to get the value of the alt-attribute from these img-tags ? Any ideas for implementing a function getAlt()?

Community
  • 1
  • 1
Hai Truong IT
  • 4,126
  • 13
  • 55
  • 102

1 Answers1

1

You can use the DomDocument class. I do this example that exports the info to an array.

Code:

<?php

    // HTML Content
    $html = '
        <img src="test.png" alt="test1" />
        <img src="test2.png" alt="test2" />
    ';

    $dom = new DomDocument;
    $dom->loadHTML($html);

    $alts = array();

    $tags = $dom->getElementsByTagName('img');
    foreach($tags as $tag) {
        $alts[$tag->attributes->getNamedItem('src')->nodeValue] = $tag->attributes->getNamedItem('alt')->nodeValue;
    }

    // DEBUG
    foreach($alts as $key => $alt) {
        echo "{$key} => {$alt}<br/>";
    }

?>
David Rodrigues
  • 12,041
  • 16
  • 62
  • 90