DOMXpath和PHP:如何在<ul>中包含一堆<li>

I have a html-document with this not-so-nice markup, without the 'ul':

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

I am now trying to "grab" all li-elements and wrap them inside an ul-list which I'd like to place in the same spot, using PHP and DOMXPath. I manage to find and "remove" the li-elements:

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

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

Maybe you can get the parentNode of the first <li> and then use the insertBefore method:

$html = <<<HTML
<p>Lorem</p>
<p>Ipsum...</p>
<li class='item'>...</li>
<li class='item'>...</li>
<li class='item'>...</li>
<div>...</div>
HTML;
$doc = new DOMDocument();
$doc->loadHTML($html);

$xpath = new DOMXpath($doc);

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

$wrapper = $doc->createElement('ul');
$elements->item(0)->parentNode->insertBefore(
    $wrapper, $elements->item(0)
);

foreach($elements as $child) {
    $wrapper->appendChild($child);
}

echo $doc->saveHTML();

Demo

Here's what you need. You may need to tweak the XPath query for your real HTML.

$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();

Running example: https://repl.it/B3UO/24