【问题标题】:php XPath reverse arrayphp XPath 反向数组
【发布时间】:2019-11-27 05:31:05
【问题描述】:

您好,我正在尝试反转 php 对象,但我没有成功 示例 html 在这里: 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 类型的对象作为数组

当我反转这个 div 时,我想用类似

的东西将它附加回原始 html
$doc->saveHTML();

TLDR:我可以得到 div 但不能反转它

感谢您的回答和最诚挚的问候

【问题讨论】:

  • 你为什么要这样做。 $divs = $divs[$i] ?我猜您正在尝试填充第二个数组,如果正确,您必须编写 $divs2[] = $divs[$i]
  • 你需要从父节点中移除子节点,颠倒顺序,然后重新添加到DOM中。
  • 您能提供示例 HTML 吗?您希望“反转”直接同级且属于同一父级的所有 div 元素吗?

标签: php xpath


【解决方案1】:

虽然我不知道这是否符合您的 html 结构要求,但如果您的所有 div 都是直接兄弟(如列表)并且它们都共享同一个父级,您可以使用以下内容。

$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_arraycloneNode 的替代解决方案

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-25
    • 2013-03-20
    • 2017-05-04
    • 2011-05-30
    • 2019-10-18
    • 2017-11-04
    • 1970-01-01
    相关资源
    最近更新 更多