Mike T
Mike T

Reputation: 359

Xpath query for finding nested element

I am having a difficult time figuring out why I'm not getting any result with this basic 2-part xpath example, and I've used Chrome's XPath Helper to confirm that the 2nd xpath Query is indeed correct and does return the row I am seeking. Can someone shed some light into why it's producing an empty result? In this example, I'm expecting to get the table row with BNY as the currency code, which is China's Yuan Renminbi. In general, I would want the table row data for any currency code that is requested, or an empty result if the currency code is not in the table.

I've also tried performing the 2nd xpath query immediately after the html load (bypassing the xpath query to retrieve JUST the table), but that's returning ALL the rows. I feel like there's something fundamentally wrong I'm doing here, but I haven't been able to discover it, as Chrome's XPath Helper works fine.

    $ccode = 'CNY';
    // Create a DOM object
    $html = new simple_html_dom();

    $url = "http://www.xe.com/symbols.php";
    // Load HTML from a URL
    $html->load_file($url);

    $table = $html->find('table.currencySymblTable', 0);        
    $xpathQuery = '//table/tbody/tr/td[2][text() = "'.$ccode.'"]/..';
    echo $xpathQuery;
    $tr = $table->find($xpathQuery);
    print_r($tr);

Upvotes: 2

Views: 1335

Answers (1)

Sahil Gulati
Sahil Gulati

Reputation: 15141

You are using wrong currency code it should be CNY and you are using wrong

XPATH should be this table[@class="currencySymblTable"]/tr/td[2][text()="CNY"]/parent::tr

 <?php

ini_set('display_errors', 1);

libxml_use_internal_errors(true);
$htmlContent = file_get_contents("http://www.xe.com/symbols.php");
$object = new DOMDocument();
$object->loadHTML($htmlContent);
$xpath = new DOMXPath($object);
$xpathQuery = '//table[@class="currencySymblTable"]/tr/td[2][text()="CNY"]/parent::tr';
$results = $xpath->query($xpathQuery);
foreach ($results as $result)
{
    print_r($result);
}

Output:

DOMElement Object
(
    [tagName] => tr
    [schemaTypeInfo] => 
    [nodeName] => tr
    [nodeValue] => China Yuan RenminbiCNY¥¥165a5  info
    [nodeType] => 1
    [parentNode] => (object value omitted)
    [childNodes] => (object value omitted)
    [firstChild] => (object value omitted)
    [lastChild] => (object value omitted)
    [previousSibling] => (object value omitted)
    [nextSibling] => (object value omitted)
    [attributes] => (object value omitted)
    [ownerDocument] => (object value omitted)
    [namespaceURI] => 
    [prefix] => 
    [localName] => tr
    [baseURI] => 
    [textContent] => China Yuan RenminbiCNY¥¥165a5    info
)

Upvotes: 1

Related Questions