简体   繁体   中英

XPath and PHP, pick specific items from query

I'm trying to loop over a HTML doc, specifically a table and pick specific table cells inside each row.

So I'm grabbing the rows "/tr" from the table I want, however, I'm now confused on how I can then when looping over the rows, pick specific "td" table cell contents?

So inside the foreach loop, I want to create headings and stick specific cells under it, does that make sense?

This is the current PHP code, which ends up echo'ing all contents of all td's inside each tr - obviously not what I want.

$version_list = new DOMDocument;
$version_list->loadHtml($version_html);

$xpath_r = new DOMXPath($version_list);
$versions = $xpath_r->query("//table[contains(@class, 'devices')]/tr");

foreach ($versions as $version)
{
    echo '<strong>Version</strong><br />';
    echo $version->nodeValue . '<br />';
}

Example HTML:

<table class="devices">
  <tr>
    <td>1.0</td>
    <td>Works</td>
  </tr>
  <tr>
    <td>2.0</td>
    <td>Broken</td>
</table>

So I want to pick cell 1 and cell 2 for each row, inside the foreach loop.

So I want something like:

echo '<strong>Version</strong><br />';
echo $version->nodeValue (first cell) . '<br />';
echo '<strong>Status</strong><br />';
echo $version->nodeValue (second cell) . '<br />';

You mean you only want to grab the version?

If so use: "//table[contains(@class, 'devices')]/tr/td[1]"

If not add your desired output.

Update:

You either need to loop over each child node or run another query again if you want an index of children that you can pluck out:

<?php
$version_list = new DOMDocument;
$version_list->loadHtml($version_html);

$xpath_r = new DOMXPath($version_list);
$versions = $xpath_r->query("//table[contains(@class, 'devices')]/tr");

foreach ($versions as $version) {
    $children = $xpath_r->query('*', $version);
    echo '<strong>Version</strong><br />';
    echo $children->item(0)->nodeValue. '<br />';
    echo '<strong>Status</strong><br />';
    echo $children->item(1)->nodeValue. '<br />';
}

https://3v4l.org/9WmnW

Or with getElementsByTagName()

<?php
$version_list = new DOMDocument;
$version_list->loadHtml('<table class="devices">
  <tr>
    <td>1.0</td>
    <td>Works</td>
  </tr>
  <tr>
    <td>2.0</td>
    <td>Broken</td>
</table>');

$xpath_r = new DOMXPath($version_list);
$versions = $xpath_r->query("//table[contains(@class, 'devices')]/tr");

foreach ($versions as $version) {
    $children = $version->getElementsByTagName('td');
    echo '<strong>Version</strong><br />';
    echo $children->item(0)->nodeValue. '<br />';
    echo '<strong>Status</strong><br />';
    echo $children->item(1)->nodeValue. '<br />';
}

https://3v4l.org/0FF1n

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