0

HTML

<div class="imgw">
    <ul>
        <li>
            <a href="http://somesites/index.html">
                <img src="http://somesites.com/picture.jpg"/>
            </a>
        </li>
    </ul>
</div>

PHP

$dom = new DOMDocument();  
$dom->loadHTML($html); 
$div = $dom->getElementByClass('imgw'); 
$links = $div->getElementsByTagName('a'); 
foreach ($links as $link) {
    $li = $link->getAttribute('href');
    echo ($li."<br>");
}

I have been looking at this (PHP DOMDocument) but I still don't understand how to make it work.

chris85
  • 23,846
  • 7
  • 34
  • 51
  • 3
    Your last paragraph looks suspiciously like the one in http://stackoverflow.com/q/20728839/1301076 I suggest you look at the answers there – rjdown Oct 31 '15 at 16:17
  • 1
    What debugging have you done? Try looking to see what `$div` and `$link` contain to help you understand. You can use print_r() to print out objects or a debugger through various IDEs. – Devon Bessemer Oct 31 '15 at 16:18
  • Questions or issues with answer provided? If that resolves the issue please mark as accepted; http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work. – chris85 Nov 01 '15 at 05:42

1 Answers1

0

Issue 1 is that you aren't using error reporting/checking error logs. Error reporting/logs would have told you:

Fatal error: Call to undefined method DOMDocument::getElementByClass()

So getElementByClass is not a function of DOMDocument. You could iterate through all divs, check if they have the class you are looking for, and then if so parse through those links.

$html = '<div class="imgw">
         <ul>
                        <li  >
                            <a href="http://somesites/index.html">
                                <img src="http://somesites.com/picture.jpg"/>
                            </a>


                        </li>
                    </ul>


            </div>';
$dom = new DOMDocument();  
$dom->loadHTML($html); 
$divs = $dom->getElementsByTagName('div');
foreach ($divs as $div){
     if(preg_match('/\bimgw\b/', $div->getAttribute('class'))) {
         $links = $div->getElementsByTagName('a');
         foreach($links as $link){
              $li = $link->getAttribute('href');
              echo ($li."<br>");
         }
     }
}

Output:

http://somesites/index.html<br>

Demo: https://eval.in/460741

chris85
  • 23,846
  • 7
  • 34
  • 51