DOMXpath&amp; PHP:如何在<ul>中包含一堆<li>

时间:2015-11-25 19:41:20

标签: php domdocument domxpath dom-traversal

我有一个带有这个不太好的标记的html文档,没有&#39; ul&#39;:

<p>Lorem</p>
<p>Ipsum...</p>
<li class='item'>...</li>
<li class='item'>...</li>
<li class='item'>...</li>
<div>...</div>

我现在正试图抓住&#34;使用PHP和DOMXPath将所有li元素包装在ul列表中,我希望将它们放在同一个位置。我设法找到&#34;删除&#34; li元素:

$elements =  $xpath->query('//li[@class="item"]');

$wrapper = $document->createElement('ul');
foreach($elements as $child) {
    $wrapper->appendChild($child);
}

2 个答案:

答案 0 :(得分:1)

也许您可以获得第一个#include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <sys/types.h> #include <sys/stat.h> int p[2]; int pid; int r; main() { char *ls[] = {"ls", NULL}; char *grep[] = {"grep", "\".c\"", NULL}; pipe(p); pid = fork(); if (pid != 0) { // Parent: Output is to child via pipe[1] // Change stdout to pipe[1] dup2(p[1], 1); close(p[0]); r = execvp("ls", ls); } else { // Child: Input is from pipe[0] and output is via stdout. dup2(p[0], 0); close(p[1]); r = execvp("grep", grep); close(p[0]); } return r; } 的{​​{1}},然后使用parentNode方法:

<li>

Demo

答案 1 :(得分:0)

这就是你需要的。您可能需要调整真实HTML的XPath查询。

$document = new DOMDocument;

// We don't want to bother with white spaces
$document->preserveWhiteSpace = false;

$html = <<<EOT
<p>Lorem</p>
<p>Ipsum...</p>
<li class='item'>...</li>
<li class='item'>...</li>
<li class='item'>last...</li>
<div>...</div>
EOT;

$document->LoadHtml($html);

$xpath = new DOMXPath($document);

$elements =  $xpath->query('//li[@class="item"]');

// Saves a reference to the Node that is positioned right after our li's
$ref = $xpath->query('//li[@class="item"][last()]')->item(0)->nextSibling;

$wrapper = $document->createElement('ul');
foreach($elements as $child) {
    $wrapper->appendChild($child);
} 

$ref->parentNode->insertBefore($wrapper, $ref);

echo $document->saveHTML();

正在运行示例:https://repl.it/B3UO/24