Use Xpath to parse HTML content with PHP

2010-09-27 @ 17:36

Information will be added soon.

$content = '<div class="test"><a href="test.se">Link</a></div>';
$dom = new DOMDocument();
$dom->loadHTML($content);
$xpath = new DomXPath($dom);
$tag = $dom->getElementsByTagName("a");
$counter = $tag->length;
for ($i = 0; $i < $counter; $i++) {
	$result = $tag->item($i)->nodeValue;
	$content = str_replace($result, '<img src="http://www.google.com/s2/favicons?domain=seo.getupdated.se&alt=feed" />'.$result, $content);
	echo $tag->item($i)-> getAttribute('href').'<br>';
}

Share
RSS-feed for comments

3 replys to “Use Xpath to parse HTML content with PHP”

  • bernd schimanski »
    2010-12-23 @ 4:48 f m

    Danke für das tolle Plugin. Eine wundervolle Idee.
    Ich wünsche Dir weiterhin kreative Ideen und maximale Erfolge, bei allem, was Du anpackst.

  • Sharecash Bypass »
    2011-04-14 @ 6:00 e m

    Would love it if someone would further explain this to me?

  • Daniel
    2011-06-02 @ 9:56 e m

    @Sharecash

    seems like this to me:

    $content = ‘Link‘;
    //create some arbitrary HTML for the example

    $dom = new DOMDocument();
    //creates special DOM object

    $dom->loadHTML($content);
    //generates the DOM for the document $content

    $xpath = new DomXPath($dom);
    //creates special xpath object that interacts with the DOM object
    //for some reason this is never used again in this script. idk why they put it in here.

    $tag = $dom->getElementsByTagName(”a”);
    //finds all occurrences of the ”a” tag in $content and stores as an array

    $counter = $tag->length;
    //gets the length of the array

    for ($i = 0; $i item($i)->nodeValue;
    //result = one individual ”a” tag (at index i in the array $tag)

    $content = str_replace($result, ”.$result, $content);
    //adding a google fav icon image in front of every ”a” tag in the array $tag

    echo $tag->item($i)-> getAttribute(‘href’).”;
    //print out all the URL’s of where the links go from each ”a” tag in $content
    }

Leave a reply