如何从PHP中的DOMDocument中删除特定元素?

时间:2014-05-03 21:26:03

标签: php dom domdocument

我想在下面的html中使用PHP中的 DOMDocument 删除名为guesstext2的元素。

我的PHP代码是

<?
$doc = new DOMDocument();
$doc->loadHTML($html);
$form = $dom->getElementsByTagName('guesstext2');

html:

<form method="post" action="./index.php_files/index.php.htm">


    <input name="sv" value="414014f687c0f5e9431972bcad9a431d"
        type="hidden">
    <!--to helper writers: please add support for captchas texts more than 8 bytes long -->
    <input name="action" value="save_capcha" type="hidden"><input
        name="id" value="25182927" type="hidden"><font color="red"><b>ATTENTION!</b></font>
    captcha is CaSe SEnseTiVE!<br> <img
        src="test_files/139905546650413.jpg" width="320"><br> <font
        color="red"><b>ATTENTION!</b></font> You're required to enter 2 words
    from this picture!<br>first word: 
    <input name="guesstext"
        id="gs1" size="17" onkeypress="document.all.counter.value=10;"
        autocomplete="off" style="font-size: 20px;" autofocus="autofocus"
        type="text"><br>second word: 
    <input name="guesstext2"
        size="17" onkeypress="document.all.counter.value=10;"
        autocomplete="off" style="font-size: 20px;" type="text"><br>
    <input onmousedown="document.all.counter.value=100;"
        onmouseover="document.cookie='showhint=true';" value=" enter "
        style="font-size: 20px;" type="submit">
    <p>Hello</p>
</form>
<input accesskey="q" value="can't read it  (alt+q)"
    style="font-size: 20px; background-color: rgb(255, 143, 130);"
    onclick="document.location='?action=make_russian&amp;id=25182927'"
    type="button"> Please refresh

2 个答案:

答案 0 :(得分:1)

$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXpath($dom);

foreach ($xpath->evaluate('//input[@name = "guesstext2"]') as $input) {
  $input->parentNode->removeChild($input);
}

答案 1 :(得分:0)

<?php

$doc = new DOMDocument();
$doc->loadHTML($html);

foreach ($dom->getElementsByTagName('input') as $input) {
    if ($input->getAttribute('name') == 'guesstext2') {
        $input->parentNode->removeChild($input);
    }
}