EventName

Relative xpath php

I am 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 several tables, so I'm trying to skip them and capture all the data. I am not sure how xpath handles requests in php. I'm currently just trying to retrieve an 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 query $ headerTag, I also tried query("./tr/td/h3", $tableNode) . How do I make this relative query?

+6
source share
2 answers

Your xpath expression is already relative:

 $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 output:

 EventName 

I hope this will be helpful.

+9
source

Actually, your html is not suitable.

As for XPATH, you can do this specifically for h3 tag targeting: -

 /table[@class='linesTbl']/tr[@class='linesHeader']/td/h3 
0
source

Source: https://habr.com/ru/post/920540/


All Articles