0

I found this code online to pull all tags from a url

<?php
$url="http://www.foo.com/xxxxxx";

$html = file_get_contents($url);

$doc = new DOMDocument();
@$doc->loadHTML($html);

$tags = $doc->getElementsByTagName('img');

foreach ($tags as $tag) {

       echo '<img src="' . $tag->getAttribute('src') . '"></img>';
}
?>

and it works fine now i am trying to adapt it to find specific tags based on class.

<?php
$url="http://www.foo.com/xxxxxx";

$html = file_get_contents($url);

$doc = new DOMDocument();
@$doc->loadHTML($html);

$tags = $doc->getElementsByClassName('bar');

foreach ($tags as $tag) {

       echo '<div>' . $tag->getAttribute('div') . '</div>';
}
?>

but I keep getting this

Fatal error: Call to undefined method DOMDocument::getElementsByClassName() in /index.php on line 9

what am i doing wrong

  • `getElementsByClassName()` is Javascript, and not part of the DOMDocument class. You could use `getElementsByTagName()` and filter the result. Or see: http://stackoverflow.com/questions/20728839/get-element-by-classname-with-domdocument-method – KIKO Software Mar 24 '15 at 22:12

1 Answers1

0

Please read the error messages!

The error message explicitly states you're calling an undefined method of an object. That alone could get you on track that something's wrong with that method.

The class synposis of DOMDocument is found here and can be used as a reference.


The problem

You're calling the wrong method. You want to call getElementByTagName() (reference here), not getElementByClassName(), which is a method of The HTML DOM Document Object in JavaScript.

jvitasek
  • 750
  • 6
  • 14