Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

relative xpath php

Tags:

php

xpath

I'm parsing html that looks like this:

  <table class="linesTbl">
        <tr class="linesHeader">
            <td><h3>EventName</h3></td>
        </tr><tr class="linesColumns">
            <td>Date</td><td class="contestLine">Description</td>
        </tr><tr class="linesAlt1">
            <td>Time</td><td>X1</td><td>Price1</td>
        </tr><tr class="linesAlt1">
            <td>&nbsp;</td><td>X2</td><td>Price2</td></tr>
</table>

There are multiple tables like this so I'm trying to loop through them and grab all of the data. I'm not sure how xpath handles queries in php. Currently I'm just trying to extract the EventName from each table.

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

foreach ($xpath->query("//table[@class = 'linesTbl']") as $tableNode){

  $headerTag = $xpath->query(".//h3", $tableNode);
  echo $headerTag->nodeValue;

}

For the $headerTag query I also tried query("./tr/td/h3", $tableNode). How do I go about doing this relative query?

like image 455
sayhey69 Avatar asked Jul 15 '12 19:07

sayhey69


1 Answers

Your xpath expression is relative already:

$headerTag = $xpath->query(".//h3", $tableNode);
                            ^       ^^^^^^^^^^
                            |    relative-to node
                       relative path

However, this returns a nodelist, not a single node, so if you do:

echo $headerTag->item(0)->nodeValue;
               ^^^^^^^^^

You can access the element you want, see the output:

EventName
like image 198
hakre Avatar answered Oct 16 '22 22:10

hakre