2011-03-24 122 views
1

嗨, $form持有該...php DOMDocument:表單元素的完整轉換?包裝和刪除?

<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> 

因爲我不知道什麼是可能與DOMDocument類,我需要尋求幫助。 我實際上有兩件事情需要在上面的$ form上轉換。

1.)label-s2email and its input#sd-email應該被包裝在一個<div class="name"> 是甚至可以選擇這兩個(通過id或for-attribute)並將這兩個包裝到一個div?

2.)是否可以使用php刪除onfocus和onblur屬性?

感謝你的幫助

+0

*(相關)* [最佳方法解析HTML](http://stackoverflow.com/questions/3577641/best-methods-to-parse-html/3577662#3577662)和[關於'DOMDocument'的Noob問題在PHP中](http://stackoverflow.com/questions/4979836/noob-question-about-domdocument-in-php/4983721#4983721) – Gordon 2011-03-24 09:27:14

回答

2

因爲我無法找到一個合適的重複,說明如何用DOM包節點,這裏是解決方案:

// 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)); 

上面的代碼將產生(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> 

注意爲了通過一個節點到saveHTML,你需要PHP 5.3.6。見

對於之前可能的解決方法。

+0

正是我想要做的事情,完美。我使用saveXML工作。 – matt 2011-03-24 13:42:36

+0

如果表單存在,是否有機會查詢?因爲一旦我提交頁面的表單重新加載並且沒有表單。在這種情況下,我的控制檯會拋出錯誤,因爲表單上的所有操作都無法完成,也沒有發現任何操作。 – matt 2011-03-24 13:46:36

+0

好吧,最簡單的方法是使用'strpos'並在加載DOM之前檢查$ form是否包含「 Gordon 2011-03-24 13:52:33

0

懶惰的解決辦法是使用phpQuery或QueryPath這允許:在這種情況下,你可以直接使用的DOMDocument

print qp($html) 
    ->find("*[onfocus], *[onblur]")->removeAttr("onblur")->removeAttr("onfocus") 
    ->top()->find("label[for=s2email], input#s2email")->wrapAll("<div class='name'></div>") 
    ->top("form")->xml(); 

雖然。只有包裝部分會更精緻一些。如果您將<label>圍繞<input>而不是使用for=name=關係,則可以簡化此操作。