dongni3854 2011-03-24 09:13
浏览 33
已采纳

php DOMDocument:表单元素的完整转换? 包装和删除?

hey guys, $form holds this...

<form method="post" action="">
    <input type="hidden" name="ip" value="127.0.0.1">
    <label for="s2email">Your Email</label>
    <input type="text" name="email" id="s2email" value="email..." size="20" onfocus="if (this.value == 'email...') {this.value = '';}" onblur="if (this.value == '') {this.value = 'email...';}">
    <input type="submit" name="subscribe" value="Subscribe">
    <input type="submit" name="unsubscribe" value="Unsubscribe">
</form>

Since I have no idea what's possible with the DOMDocument class I need to ask for help. I actually have two things I need to transform on the $form above.

1.) label-s2email and its input#sd-email should be wrapped inside a <div class="name"> Is that even possible to select those two (via id or for-attribute) and wrap those two into a div?

2.) Is it possible to remove the onfocus and onblur attribute with php?

thank you for your help

  • 写回答

2条回答 默认 最新

  • doumang20060820 2011-03-24 10:13
    关注

    Since I cannot find a suitable duplicate that shows how to wrap nodes with DOM, here is the solution:

    // Setup DOMDocument and XPath
    $dom = new DOMDocument;
    $dom->loadHTML($form);
    $xpath = new DOMXPath($dom);
    
    // Create <DIV> with class attribute name
    $div = $dom->createElement('div');
    $div->setAttribute('class', 'name');
    
    // Find <input id="s2email"> and remove event attributes
    $input = $xpath->query('/html/body/form/input[@id="s2email"]')->item(0);
    $input->removeAttribute('onfocus');
    $input->removeAttribute('onblur');
    
    // Find <label for="s2email"> and insert new DIV before that
    $label = $xpath->query('/html/body/form/label[@for="s2email"]')->item(0);
    $label->parentNode->insertBefore($div, $label);
    
    // Move <label> and <input> into the new <div>
    $div->appendChild($label);
    $div->appendChild($input);
    
    // Echo the <form> outer HTML
    echo $dom->saveHTML($dom->getElementsByTagName('form')->item(0));
    

    The above code will produce (live demo):

    <form method="post" action="">
        <input type="hidden" name="ip" value="127.0.0.1"><div class="name">
    <label for="s2email">Your Email</label><input type="text" name="email" id="s2email" value="email..." size="20">
    </div>
        <input type="submit" name="subscribe" value="Subscribe"><input type="submit" name="unsubscribe" value="Unsubscribe">
    </form>
    

    Note that in order to pass a node to saveHTML, you need PHP 5.3.6. See

    for possible workarounds before that.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 手机连接电脑热点显示无ip分配
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大