【问题标题】:How to remove a specific element from DOMDocument in PHP?如何从 PHP 中的 DOMDocument 中删除特定元素?
【发布时间】:2014-05-03 21:26:02
【问题描述】:

我想在下面的 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

【问题讨论】:

标签: php dom domdocument


【解决方案1】:
$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXpath($dom);

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

【讨论】:

    【解决方案2】:
    <?php
    
    $doc = new DOMDocument();
    $doc->loadHTML($html);
    
    foreach ($dom->getElementsByTagName('input') as $input) {
        if ($input->getAttribute('name') == 'guesstext2') {
            $input->parentNode->removeChild($input);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-27
      • 1970-01-01
      • 2011-01-19
      • 2012-02-07
      • 2013-02-22
      相关资源
      最近更新 更多