我一直在黑客這一段時間,只是似乎不能得到正確的。DOMDocument獲取每個匹配元素的nodeValue
當腳本元素的數量變化時,如何獲取所有腳本元素的內容。我的例子標記看起來是這樣的:只有當我把劇本靜態的,所以顯然我不是遍歷數組在正確的數量
<div></div>
<iframe><iframe>
<script>xxxx</script>
<script>xxxx</script>
<script>xxxx</script>
我至今的作品,但是我完全被DOMXPath documentation拋出該怎麼辦它。這是我到目前爲止:
$dom = new DOMDocument();
$dom->preserveWhiteSpace = true;
@$dom->loadHtml($form_content);
$xpath = new DOMXPath($dom);
$items = $xpath->query('//script');
foreach ($items as $item) {
$scriptContents = $item->previousSibling->previousSibling->nodeValue . "\r\ n\r\n";
$scriptContents .= $item->previousSibling->nodeValue . "\r\n\r\n";
$scriptContents .= $item->nodeValue . "\r\n\r\n";
}
echo $scriptContents;
我該怎麼辦?我一直在搜索一段時間,但似乎可以應用一種可行的解決方案。在此先感謝 - b
我不理解的問題。如果你有3個'script'標籤,你的foreach將會循環3次,如果你有10個'script'標籤,它會迭代10次。你看到哪些不同於此的行爲?你能顯示HTML會導致這不是真的嗎?現在我不清楚你正在用'$ scriptContents'來做什麼,因爲每次迭代都會覆蓋變量。也許這解釋了你期望發生的事情和實際發生的事情的不同。對我來說,它看起來像只會回顯最後腳本標記的最後三個兄弟節點。 –
檢查[這個答案](http://stackoverflow.com/questions/14308778/simple-dom-and-li/14309058#14309058)和使用的庫的參考,它是超級簡單的,並會讓你加載'HTML'也來自'string'。 –
@MikeBrant - 新的一天,我看到它,我忽略了一個基本的錯誤,因爲我認爲我在做DOMXPath錯誤。當你指出'$ scriptContents'是問題時,我需要首先聲明它,然後'$ scriptContents。= $ item-> previousSibling-> nodeValue;'將按照預期得到所有腳本節點的內容。如果你想把它寫成答案,我會接受它。 – orionrush