gpt4 book ai didi

php - 使用 phpquery 替换元素(jquery 的 php 版本)

转载 作者:可可西里 更新时间:2023-11-01 00:52:46 25 4
gpt4 key购买 nike

我想替换所有<span>带有 <p> 的标签使用 phpquery。我的代码有什么问题?它找到了 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;
}

也许这可以让您在如何在 phpQuery 中进行替换方面找到正确的方向?


编辑:

我给了 replaceWith 的 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;

我找不到任何方法在一行中使用链式方法调用来完成此操作。

关于php - 使用 phpquery 替换元素(jquery 的 php 版本),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3593968/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com