我想用phpquery用<span>替换所有<p>标记。我的代码怎么了?它找到span但replaceWith函数没有做任何事情。

$event = phpQuery::newDocumentHTML(file_get_contents('event.html'));
$formatted_event = $event->find('span')->replaceWith('<p>');

本文档表明这是可能的:
http://code.google.com/p/phpquery/wiki/Manipulation#Replacing
http://api.jquery.com/replaceWith/
这是在代码中返回的带有和不带->replaceWith('<p></p>')的html:
<span class="Subhead1">Event 1<br></span><span class="Subhead2">Event 2<br>
    August 12, 2010<br>
    2:35pm <br>
    Free</span>

最佳答案

如果你不介意一个简单的domdocument解决方案(domdocument是在phpquery的框架下用来解析html片段的),我刚才做了类似的事情。我修改了代码以满足您的需要:

$document = new DOMDocument();

// load html from file
$document->loadHTMLFile('event.html');

// find all span elements in document
$spanElements = $document->getElementsByTagname('span');
$spanElementsToReplace = array();

// use temp array to store span elements
// as you cant iterate a NodeList and replace the nodes
foreach($spanElements as $spanElement) {
  $spanElementsToReplace[] = $spanElement;
}

// create a p element, append the children of the span to the p element,
// replace span element with p element
foreach($spanElementsToReplace as $spanElement) {
    $p = $document->createElement('p');

    foreach($spanElement->childNodes as $child) {
        $p->appendChild($child->cloneNode(true));
    }

    $spanElement->parentNode->replaceChild($p, $spanElement);
}

// print innerHTML of body element
print DOMinnerHTML($document->getElementsByTagName('body')->item(0));


// --------------------------------


// Utility function to get innerHTML of an element
// -> "stolen" from: http://www.php.net/manual/de/book.dom.php#89718
function DOMinnerHTML($element) {
    $innerHTML = "";
    $children = $element->childNodes;
    foreach ($children as $child)
    {
        $tmp_dom = new DOMDocument();
        $tmp_dom->appendChild($tmp_dom->importNode($child, true));
        $innerHTML.=trim($tmp_dom->saveHTML());
    }
    return $innerHTML;
}

也许这可以让你在PHPQuQuy中进行替换的正确方向?
编辑:
我给了replace的jquery文档另一个外观,在我看来,您必须传递整个html片段,您希望它是您新的、被替换的内容。
这段代码对我有效:
$event = phpQuery::newDocumentHTML(...);

// iterate over the spans
foreach($event->find('span') as $span) {
// make $span a phpQuery object, otherwise its just a DOMElement object
$span = pq($span);
// fetch the innerHTMLL of the span, and replace the span with <p>
$span->replaceWith('<p>' . $span->html() . '</p>');
}

print (string) $event;

我找不到在一行中使用链式方法调用的方法。

07-26 06:13