使用PHP,我正在尝试在已解析的HTML中添加div,插入位置取决于现有标记的ID。
我得到一个生成的HTML文件(我无法控制),它基本上是只读的。 我的工作是获取HTML文件,添加几个div(按钮和其他东西),然后重新发送。
这是一个有点棘手的地方:我需要添加div(我用按钮和东西添加的div)取决于可以在HTML文件中多次出现的div ID。
为了使我添加的div正常工作,必须在标记的可识别div的父div之前添加它。
简单地说:
{{1}}
答案 0 :(得分:3)
你绝对是最好的选择,imo将使用PHP的原生DOMDocument: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>