Search code examples
phpxpathdomxpath

xPath, getting tabular data


I have a HTML thus like:

<table>
  <tr>
     <th>Name</th>
     <th>Email</th>
     <th>Age</th>
  </tr>
  <tr>
     <td>Joe Bloggs</td>
     <td>[email protected]</td>
     <td>40</td>
  </tr>
  <tr>
     <td>John Doe</td>
     <td>[email protected]</td>
     <td>40</td>
  </tr>
 </table>

Is there a way using xPath to get the first 2 columns, i.e the Name and Email fields?

I can get the table data using $data = $xpath->query( '//table'); just unsure how to get only the first 2 columns.

Many thanks


Solution

  • Get the first two td's:

    //table/tr/td[position() <= 2]