简体   繁体   中英

Warning: DOMXPath::query(): Invalid expression

I'm an Xpath newbie. I want to loop through the result of a cURL query and print each element of the only table on the page.

I've used the Xpath plugin for Firefox to obtain my expression and my table is structured as follows:

<table>
<tr class="listItemOneBg">
    <td valign="top">
        SMITH
    </td>
    <td valign="top">
        WILLIAM C C
    </td>
    <td valign="top">
        Male
    </td>
    <td valign="top">

    </td>
    <td valign="top">

    </td>
    <td valign="top">

    </td>
    <td valign="top">

    </td>
    <td valign="top">
        BLACKWOOD
    </td>
    <td valign="top">
        61
    </td>
    <td valign="top">
        1924
    </td>
    <td valign="top">
        <a target="_blank" href='XXX'>
            order</a>
    </td>
</tr>

<tr class="listItemTwoBg">
    <td valign="top">
        SMITH
    </td>
    <td valign="top">
        WILLIAM C PAGE-
    </td>
    <td valign="top">
        Male
    </td>
    <td valign="top">

    </td>
    <td valign="top">

    </td>
    <td valign="top">

    </td>
    <td valign="top">

    </td>
    <td valign="top">
        SWAN
    </td>
    <td valign="top">
        9
    </td>
    <td valign="top">
        1914
    </td>
    <td valign="top">
        <a target="_blank" href='XXY'>
            order</a>
    </td>
</tr>       

Here's the code I've tried so far. I get a message"Warning: Invalid argument supplied for foreach()". What am I doing wrong?

$page = curl_exec($ch);
curl_close($ch);

// Create new PHP DOM document
$dom = new DOMDocument;
// Load html from curl request into document model
@$dom->loadHTML($page);
$xpath = new DOMXPath($dom);

$tableRows = $xpath->query("id('divResults')/table/tbody/tr");
foreach ($tableRows as $row) {
     // fetch all 'tds' inside this 'tr'
    $td = $xpath->query('td', $row);
    echo $td->item(1)->textContent;
}

Assuming the table you're after is actually in a <div id="divResults"> ...

$tableRows = $xpath->query('//div[@id="divResults"]/table/tbody/tr');
foreach ($tableRows as $row) {
    $cells = $row->getElementsByTagName('td');
}

That's a non-standard XPath expression. It cannot work in DOMXPath .
(Downvoters, the expression has been edited since the question was posted. Cheers!)

This is where you learn XPath :

PS : It's where I learnt it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM