PHP:xpath替换内容标签

时间:2018-09-01 13:57:33

标签: php xpath

我想更改该内容:

Cambio turno (FL) HMLN 16:00-20:00 del 08/09/2018 con (FL) HMLN 15:00-19:00 del 05/09/2018

进入:

<a href="prova.it">Cambio turno (FL) HMLN 16:00-20:00 del 08/09/2018 con (FL) HMLN 15:00-19:00 del 05/09/2018</a>

这是html页面的摘录:

<td class="tdReset">
  <table id="ctl00_ctl00_mainContent_bodyContent_TblOperazioni_8529448" class="tblReset">
    <tbody>
      <tr>
        <td operazione="accetta"><input id="ctl00_ctl00_mainContent_bodyContent_chkAccetta_8529448" name="ctl00$ctl00$mainContent$bodyContent$chkAccetta_8529448" onclick="SelezioneUnivocaAccetta(this);AccettaRifiutaStessaRichiesta(this);" tabindex="0" type="checkbox"><label for="ctl00_ctl00_mainContent_bodyContent_chkAccetta_8529448">Accetta</label></td>
      </tr>
      <tr>
        <td operazione="rifiuta">
          <input id="ctl00_ctl00_mainContent_bodyContent_chkRifiuta_8529448" name="ctl00$ctl00$mainContent$bodyContent$chkRifiuta_8529448" onclick="AccettaRifiutaStessaRichiesta(this);" tabindex="0" type="checkbox">
          <label for="ctl00_ctl00_mainContent_bodyContent_chkRifiuta_8529448">Rifiuta</label>
        </td>
      </tr>
    </tbody>
  </table>
</td>
<td>sab 01/09/2018</td>
<td>Proposta</td>
<td><span style="padding-left:15px;"> Jhon</span></td>
<td class="textWrap">Cambio turno (FL) HMLN 16:00-20:00 del 08/09/2018 con (FL) HMLN 15:00-19:00 del 05/09/2018</td>
<td></td>
<td></td>

我在PHP中创建的代码如下:

 $xpR=new DOMXPath( $dom_richieste_r );
  $operazione_select= $xpR->query( '//label[contains(.,"Accetta")]' );
  if( !empty( $operazione_select )){
    foreach( $operazione_select as $node2 ){
       //$node2->parentNode->parentNode->parentNode->parentNode->parentNode->firstChild->nextSibling->nextSibling->nextSibling->nextSibling->C14N(); // get Cambio turno (FL) HMLN 16:00-20:00 del 08/09/2018 con (FL) HMLN 15:00-19:00 del 05/09/2018 

       $newelement = $dom_richieste_r->createElement('a', 'prova'); 
       $newelement->setAttribute("href", "http://prova.it");
       $link_1=$node2->parentNode->parentNode->parentNode->parentNode->parentNode->firstChild->nextSibling->nextSibling->nextSibling->nextSibling;

      $link_1->replaceChild($newelement, $link_1);

    }
   } 

1 个答案:

答案 0 :(得分:1)

我不知道您为什么必须相对于“接受”按钮选择有问题的节点,但是您可以使用单个XPath查询来做到这一点

//*[td/table/tbody/tr/td/label[contains(.,"Accetta")]]/td[5]

XPath Demo

,然后像这样替换内部文本:

$dom = new DOMDocument();
$dom->loadHTML($str);
$xpath = new DOMXPath($dom);
$operazione_select = $xpath->query('//*[td/table/tbody/tr/td/label[contains(.,"Accetta")]]/td[5]');
foreach ($operazione_select as $node) {
    //create link
    $newlink = $dom->createElement('a', $node->nodeValue);
    $newlink->setAttribute('href', 'http://prova.it');
    $node->removeChild($node->childNodes->item(0));
    $node->appendChild($newlink);    
}