php XPath 反向数组 [英] php XPath reverse array
问题描述
您好,我正在尝试反转 php 对象,但没有成功示例 html 在这里:sample_html
Hi there I am trying to reverse php object but I am not successful sample html is here: sample_html
$html = file_get_contents($file);
$doc = new DOMDocument();
@$doc->loadHTML($html);
$xpath = new DOMXpath($doc);
//get the element you want to append to
$classname = 'pam _3-95 _2pi0 _2lej uiBoxWhite noborder';
$divs = $xpath->query("//*[contains(@class, '$classname')]");
var_dump($divs[0]);
$count = count($divs);
$divs2 = array();
for ($i = $count-1; $i >= 0; $i--) {
$divs = $divs[$i];
}
var_dump($divs[0]);
它给出了不能使用 DOMElement 类型的对象作为数组在
its giving Cannot use object of type DOMElement as array in
当我反转这个 div 时,我想用类似
when I have this div reversed I would like to append it back to original html with something like
$doc->saveHTML();
TLDR:我可以得到 div 但不能反转它
TLDR: I can get the div but cannot reverse it
感谢您的回答和问候
推荐答案
虽然我不知道这是否符合您的 html 结构要求,但是如果您的所有 div 都是直接兄弟(如列表)并且它们都共享相同的家长,您可以使用以下内容.
Whilst I don't know if this meets your html structure requirements, but if all your divs are immediate siblings (like a list) and they all share the same parent, you can use the following.
$divs = $xpath->query("//*[contains(@class, '$classname')]");
for( $x = 0; $x < $divs->length ; $x++ )
{
if( $divs[ $x ] !== $divs[ $x ]->parentNode->firstChild )
{
$divs[ $x ]->parentNode->insertBefore( $divs[ $x ], $divs[ $x ]->parentNode->firstChild );
}
}
<小时>
利用 iterator_to_array
和 cloneNode
$divs = iterator_to_array( $xpath->query("//*[contains(@class, '$classname')]") );
$keys = array_reverse( array_keys( $divs ) );
foreach( $divs as $x => $div )
{
$div->parentNode->replaceChild( $divs[ $keys[ $x ] ]->cloneNode(true), $div );
}
这篇关于php XPath 反向数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!