Skip to content Skip to sidebar Skip to footer

Xpath Query For Html Table Within Xml In Php Domdocument

I have an XML file with following tree structure. );

I assume that $xpathvar here is of type DOMXPath. If so, it has a length property as described here. Instead of using foreach, simply use:

$length = $xpathvar->query('//item/title')->length;

Now I want to pick the text node values for //channel/item/title

Which you can get with the expression //channel/item/title/text().

and href value for //channel/item/description/table/tr/td[1]/a[1] (with a text node value = "[link]")

Your expression here selects any tr, the first td under that, then the first a. But the first a does not have a value of "[link]" in your source. If you want that, though, you can use:

//channel/item/description/table/tr/td[1]/a[1]/@href

but it looks like you rather want:

//channel/item/description/table/tr/td/a[. = "[link]"][1]/@href

which finds the first a element in the tree that has the value (text node) that is "[link]".

Above in 2nd case, I am looking for the value of 2nd a (with a text node value = "[link]"), inside 2nd td inside tr, table, description, item, channel.

Not sure if this was a separate question or meant to explain the previous one. Regardless, the answer the same as in the previous one, unless you explicitly want to search for 2nd a etc (i.e., search by position), in which case you can use numeric predicates.


Note: you start most of your expressions with //expr, which essentially means: search the whole tree at any depth for the expression expr. This is potentially expensive and if all you need is a (relative) root node for which you know the starting point or expression, it is better, and far more performant, to use a direct path. In your case, you can replace //channel for /*/channel (because it is the first under the root element).

Solution 2:

I finally could make it work with the code below

$url = "https://www.example.com/r/videos/.xml";
$feed_dom = new domDocument; 
$feed_dom->load($url); 
$feed_dom->preserveWhiteSpace = false;
$items = $feed_dom->getElementsByTagName('item');

foreach($itemsas$item){
    $title = $item->getElementsByTagName('title')->item(0)->nodeValue;
    $desc_table = $item->getElementsByTagName('description')->item(0)->nodeValue;
    echo$title . "<br>";

    $table_dom = new domDocument;
    $table_dom->loadHTML($desc_table);
    $xpath = new DOMXpath($table_dom);
    $table_dom->preserveWhiteSpace = false;
    $yt_link_node = $xpath->query("//table/tr/td[2]/a[2]");

    foreach($yt_link_nodeas$yt_link){

        $yt = $yt_link->getAttribute('href');
        echo$yt . "<br>";
        echo"<br>";
    }
}

I thank Abel, your help was greatly useful to achieve the tasks. :)

Post a Comment for "Xpath Query For Html Table Within Xml In Php Domdocument"