简体   繁体   中英

How to select the Last elements attribute and change its value on html with php

HTML file (Demo)

<table>
 <tr>
 <td rowspan="1"> 1 </td>
 <td rowspan="1"> 2 </td>
 <td rowspan="1"> 3 </td>
 </tr>
 </table>

When I'll trigger the PHP file, it should get the last rowspan of the HTML file and change its value to 2.

$html = new DOMDocument(); 
$html->loadHTMLFile($file);
// find the last td by xpath and set value
$xpath = new DOMXpath($html);
$td = $xpath->query("(//td)[last()]")->item(0)->setAttribute('rowspan', 2);

echo $html->saveHTML();

UPDATE

$xpath = new DOMXpath($html);
$tds = $xpath->query("//td[position()=last() or (position()=last()-1)]");

foreach($tds as $td)
   $td->setAttribute('rowspan', 5);

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