treehouse : what would you like to learn today?
Web Design Web Development iOS Development

PHP Simple HTML DOM Parser [HELP]

  • Hey,

    I am working on an app in which I am using PHP Simple HTML DOM Parser. Now what is I have for example following HTML which I have fetched in sting:

    <table> <tbody> <tr> <th>Column1</th> <th>Column2</th> <th>Column3</th> </tr> <tr> <td><a href="#">First Link</a></td> <td>Some content here <td><a href="#">Another Link</a></td> </tr> <tr> <td><a href="#">First Link</a></td> <td>Some content here <td><a href="#">Another Link</a></td> </tr> </tbody> </table>

    Now what I want is to fetch first link of every

    element and echo it's src on screen.
  • ...I'm assuming that <table> is the HTML in question?

    (You can post HTML in your comments by writing &lt; in place of <.)

    what I want is to fetch first link of every element

    Do you mean "links in the first column"?

    I've never used this class, but according to the page you linked to, it would be as simple as loading the HTML string and using the find() method:

      // find each table row
      foreach( $HTMLstring->find( 'tr' ) as $tr ){ 
          // find the first column in each row
          foreach( $tr->find( 'td',0 ) ){
              // if there is an anchor
              if( ($a = $td->find( 'a',0 ) ) ){ 
                  // if the anchor is a hyperlink, print the href
                  if( isset( $a->href ) ){ print $a->href; }
              }
          }
      }
    

    Have you tried anything like this? If you need help, post the code you've tried so far and describe what problems you've encountered.

  • I have tried this kind of code including this one which you posted but it is showing:

    Invalid argument supplied for foreach()

    as what I understand that when we are finding first occurrence of

    we can't make it in loop.
  • That means that the parser didn't find any matching elements:

    ...returns element object or null if not found.
    [emphasis added]

    You can check like so:

      if( ($html = $HTMLstring->find( 'tr' )) !== null ){
          foreach // . . .etc.
    

    If you'd like more help, post your code.