你絕對是最好的選擇,國際海事組織將使用PHP的原生DOM文檔:http://php.net/manual/en/class.domdocument.php
有相當的學習曲線,這讓我激動的東西,應該讓你去在正確的方向 - 如果不提供一個解決方案。我已經包括逐行評論這裏要說明每一個步驟:
// the filename you want to parse
$filename = './test.html';
// an array of replacement html snippets and the id of the child element.
// html will be inserted before parent of each child with a matching ID as you described
$replacements = [
[
'id' => 'myId',
'insert' => '<button>Insert before parent of #myId</button>'
],
[
'id' => 'myId2',
'insert' => '<button>Insert before parent of#myId2</button>'
]
];
// instantiate DOMDocument and read the html file
libxml_use_internal_errors(true);
$dom = new DOMDocument();
$dom->loadHTMLFile('./test.html');
// get an array of all dom elements
$elements = $dom->getElementsByTagName('*');
// iterate through dom elements
foreach($elements as $element) {
// check if this element has an 'id' attribute
if ($element->hasAttribute('id')) {
// iterate through replacement array
foreach ($replacements as $i => $replacement) {
// if element's id is a match then add this node to our array
if ($element->getAttribute('id') == $replacement['id']) {
$replacements[$i]['nodes'][] = $element;
}
}
}
}
// iterate through replacements again
foreach ($replacements as $replacement) {
// iterate through nodes we found which matched
foreach ($replacement['nodes'] as $node) {
// create a DOMDocument node from an html string
$html = $dom->createDocumentFragment();
$html->appendXML($replacement['insert']);
// insert this node before parent
$node->parentNode->parentNode->insertBefore($html,$node->parentNode);
}
}
// output the revised html
echo $dom->saveHTML();
// note - if your html doesn't have <html> and <body> tags they will be automatically added by DOMDOcument
// you can work around this and get only body innerhtml with something like this
echo str_replace(['<body>','</body>'],'',$dom->saveHTML($dom->getElementsByTagName('body')->item(0)));
我創建一個名爲test.html的以下HTML測試文檔。我故意用myId
兩次證明這將在事實上比賽無論有效性的每一個元素:
<div> // no tags no info just a simple div
<div id="myId">
... some html
</div>
</div>
<div> // no tags no info just a simple div
<div id="myId2">
... some html
</div>
</div>
<div> // no tags no info just a simple div
<div id="myId">
... some html
</div>
</div>
PHP代碼上面的輸出如下:
<button>Insert before parent of #myId</button><div> // no tags no info just a simple div
<div id="myId">
... some html
</div>
</div>
<button>Insert before parent of #myId2</button><div> // no tags no info just a simple div
<div id="myId2">
... some html
</div>
</div>
<button>Insert before parent of #myId</button><div> // no tags no info just a simple div
<div id="myId">
... some html
</div>
</div>
一個例子就好了 – Jah
好即時通訊試圖找到一種方法來搜索HTML文件中的標籤獲取父標籤,並在它之前插入一串代碼。 得到父標籤是困擾我的一個問題 – Z3R0
爲什麼不構造一個if/else語句?如果($ divID ==='abc'){insert ...} else {do something instead} – Kray