如何在 php 中查看 DOMNodeList 对象的数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1365756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:13:13  来源:igfitidea点击:

How to view DOMNodeList object's data in php

phpdomxpathdomdocument

提问by ahmed

when I want to test php array I use the following code

当我想测试 php 数组时,我使用以下代码

    print_r($myarray);

but know I want to see the data of an object my object is

但知道我想查看我的对象所在的对象的数据

    $xpath = new DOMXPath($doc);
    $myobject = $xpath->query('//*[ancestor-or-self::a]');

when I use

当我使用

    print_r($myobject);

I get that output

我得到那个输出

    DOMNodeList Object ( )

I want to iterate through the values of this object to test the result of my query?

我想遍历这个对象的值来测试我的查询结果?

回答by ghbarratt

DOMNodeList is an interesting object, one that you will not get much information from using print_ror var_dump.

DOMNodeList 是一个有趣的对象,您不会从使用print_r或 中获得太多信息var_dump

There are many ways to view the data of a DOMNodeList object. Here is an example:

有很多方法可以查看 DOMNodeList 对象的数据。下面是一个例子:

$xpath = new DOMXpath($dom);
$dom_node_list = $xpath->query($your_xpath_query);
$temp_dom = new DOMDocument();
foreach($dom_node_list as $n) $temp_dom->appendChild($temp_dom->importNode($n,true));
print_r($temp_dom->saveHTML());

(Of course use saveXML instead of saveHTML if you are dealing with XML.)

(当然,如果您正在处理 XML,请使用 saveXML 而不是 saveHTML。)

A DOMNodeList can be iterated over like an array. If you want to pull the data out of the DOMNodeList object and put it into a different data structure, such as an array or stdClass object, then you simply iterate through the "nodes" in the DOMNodeList, converting the nodes' values and/or attributes (that you want to have available) before adding them to the new data structure.

DOMNodeList 可以像数组一样迭代。如果您想从 DOMNodeList 对象中提取数据并将其放入不同的数据结构中,例如数组或 stdClass 对象,那么您只需遍历 DOMNodeList 中的“节点”,转换节点的值和/或在将它们添加到新数据结构之前(您希望具有可用的属性)。

回答by danhdds

It's possible to navigate through the nodes by using a simple foreach as follow:

可以使用简单的 foreach 来浏览节点,如下所示:

foreach ($myobject as $node) {

  echo $node->nodeValue, PHP_EOL;

} // end foreach 

Hope that it can help others, the important pieces of code are the

希望它可以帮助其他人,重要的代码是

foreach 

and the item

和项目

$node->nodeValue

for more details regarding this class please visit:

有关此课程的更多详细信息,请访问:

http://php.net/manual/en/class.domnodelist.php

http://php.net/manual/en/class.domnodelist.php

回答by Steven Vachon

Someone wrote a great getArray() function: http://www.php.net/manual/en/class.domdocument.php#101014

有人写了一个很棒的 getArray() 函数:http://www.php.net/manual/en/class.domdocument.php#101014

回答by Greg Young

For some reason, I've been unable to get the saveHTML/saveXML methods to work. So I wrote my own recursive routine which works for me:

出于某种原因,我一直无法使用 saveHTML/saveXML 方法。所以我写了我自己的递归例程,它对我有用:

function pvIndent ( $ind ) {
    for ($i=0;$i<$ind;$i++)
        print ( "   " );
}

function pvPrint_r ( $val ) {
    echo '<pre>';
    print_r ( $val );
    echo '</pre>';
}

function pvDOMNodeListPrint_r_ ( $ind,$DOMNodeList ) {
    for ($item=0;$item<$DOMNodeList->length;$item++) {
        $DOMNode = $DOMNodeList->item($item);
        if ($DOMNode->nodeName != "#text") {
            pvIndent ( $ind );
            print $DOMNode->nodeName;
            if ($DOMNode->nodeValue)
                print " = " . trim($DOMNode->nodeValue);
            print "\n";
            if ($DOMNode->attributes)
                for ($attr=0;$attr<$DOMNode->attributes->length;$attr++) {
                    $DOMNodeAttr = $DOMNode->attributes->item($attr);
                    pvIndent ( $ind+1 );
                    print "@" . $DOMNodeAttr->nodeName . " = " . trim($DOMNodeAttr->nodeValue) . "\n";
                }
            if ($DOMNode->childNodes)
                pvDOMNodeListPrint_r_ ( $ind+1,$DOMNode->childNodes );
        }
    }
}

function pvDOMNodeListPrint_r ( $DOMNodeList ) {
    echo '<pre>';
    pvDOMNodeListPrint_r_ ( 0,$DOMNodeList );
    echo '</pre>';
}

Call pvDOMNodeListPrint_r with your result from a query on an XDOMPath object.

使用 XDOMPath 对象上的查询结果调用 pvDOMNodeListPrint_r。

Notes :

注意事项:

pv is just the prefix I use to avoid name space pollution - feel free to edit it out.

pv 只是我用来避免名称空间污染的前缀 - 随意编辑它。

pre tags are used so white space and newlines are handle properly for formatting when output in the body of your html, which is where I generally need such debugging statements - you can format to your taste.

使用 pre 标记,以便在 html 正文中输出时正确处理空格和换行符以进行格式化,这通常是我需要此类调试语句的地方 - 您可以根据自己的喜好进行格式化。

I've explicitly skipped DOMNode's with the name "#text" as these seem to repeat the text already contained in the parent node. I'm not sure this correct for all valid XDOMPath's loaded with HTML, but I've not yet seen an exception - you can always eliminate the exclusion if you don't mind the usual redundancy.

我已经明确跳过了名称为“#text”的 DOMNode,因为它们似乎重复了父节点中已经包含的文本。我不确定这对于所有加载了 HTML 的有效 XDOMPath 是否正确,但我还没有看到异常 - 如果您不介意通常的冗余,您总是可以消除排除。

回答by Kuko Kukanovic

A bit late in the game, but perhaps it helps someone...

游戏有点晚了,但也许它可以帮助某人......

Be aware of utf-8 output when using the dom/xpath object itself.

使用 dom/xpath 对象本身时,请注意 utf-8 输出。

If you would output the nodeValue directly, you would get corrupted characters e.g.:

如果你直接输出 nodeValue,你会得到损坏的字符,例如:

???????? ???1????”?”????¤
ìì ?1?””ì¤ í°ì  íì¤

You have to load your dom object with the second param "utf-8", new \DomDocument('1.0', 'utf-8'), but still when you print the dom node list/element value you get broken characters:

您必须使用第二个参数“utf-8”加载 dom 对象new \DomDocument('1.0', 'utf-8'),但是当您打印 dom 节点列表/元素值时,您仍然会得到损坏的字符:

echo $contentItem->item($index)->nodeValue

echo $contentItem->item($index)->nodeValue

you have to wrap it up with utf8_decode:

你必须用 utf8_decode 把它包起来:

echo utf8_decode($contentItem->item($index)->nodeValue) //output: 者不終朝而會,愚者可浹旬而學

echo utf8_decode($contentItem->item($index)->nodeValue) //output: 者不終朝而會,愚者可浹旬而學

回答by Scott Lundberg

How about a recursive function?

递归函数怎么样?

Function XMLPrint_r($d_DomNode) {
    print $d_DomNode->$nodeName." ".$d_DomNode->$nodeValue."<br>";
    Foreach($d_DomNode->$childNodes as $d_ChildNode) {
        print " ";
        XMLPrint_r($d_ChildNode);
    }
}

I did not test this, but you get the idea.

我没有测试这个,但你明白了。

回答by Ryan

var_dump($myobject);may be what you're looking for

var_dump($myobject);可能就是你要找的

回答by zombat

Your xpath query is not matching anything in your XML.

您的 xpath 查询与您的 XML 中的任何内容都不匹配。

From the DomXPath::query manual page:

DomXPath::query 手册页

Returns a DOMNodeList containing all nodes matching the given XPath expression . Any expression which do not return nodes will return an empty DOMNodeList.

返回包含与给定 XPath 表达式匹配的所有节点的 DOMNodeList。任何不返回节点的表达式都将返回一个空的 DOMNodeList。

回答by madprogrammer

After much debugging I found out that all DOM objects are invisible to var_dump() and print_r(), my guess is because they are C objects and not PHP objects. So I tried saveXML(), which works fine on DOMDocument, but is not implemented on DOMElement.

经过多次调试,我发现所有 DOM 对象对 var_dump() 和 print_r() 都是不可见的,我猜是因为它们是 C 对象而不是 PHP 对象。所以我尝试了 saveXML(),它在 DOMDocument 上工作正常,但没有在 DOMElement 上实现。

The solution is simple (if you know it):

解决方案很简单(如果你知道的话):

$xml = $domElement->ownerDocument->saveXML($domElement);