如何使用PHP DOMDocument从节点值获取文本

时间:2022-10-27 07:53:13

I am trying to loop through nodeValues of objects outputed by DOMDocument and get the text output but I am not sure how to go about doing it. My code and output are below.

我试图循环DOMDocument输出的对象的nodeValues并获取文本输出,但我不知道如何去做。我的代码和输出如下。

From the output below I need to get only the NodeValue text output, e.g. "Bar and Hotel".

从下面的输出我只需要获得NodeValue文本输出,例如“酒吧和酒店”。

$dom = new DOMDocument;
                @$dom->loadHTML($v);

                $xpath = new DomXpath($dom);
                $div = $xpath->query('//*[@class="type-cat"]'); 
                foreach ($div as $a) {

                    var_dump($a );      
                }

object(DOMElement)#22 (18) { 
    ["tagName"]=> string(2) "h5"
    ["schemaTypeInfo"]=> NULL
    ["nodeName"]=> string(2) "h5"
    ["nodeValue"]=> string(41) " Bar and Hotel" 
    ["nodeType"]=> int(1)
    ["parentNode"]=> string(22) "(object value omitted)" 
    ["childNodes"]=> string(22) "(object value omitted)" 
    ["firstChild"]=> string(22) "(object value omitted)"
    ["lastChild"]=> string(22) "(object value omitted)"
    ["previousSibling"]=> string(22) "(object value omitted)"
    ["nextSibling"]=> string(22) "(object value omitted)" 
    ["attributes"]=> string(22) "(object value omitted)" 
    ["ownerDocument"]=> string(22) "(object value omitted)" 
    ["namespaceURI"]=> NULL 
    ["prefix"]=> string(0) "" 
    ["localName"]=> string(2) "h5" 
    ["baseURI"]=> NULL
    ["textContent"]=> string(41) " Bar and Hotel" 
}

1 个解决方案

#1


0  

As you can see from the dump of the node object, the nodeValue is what you are looking for. You access it with

从节点对象的转储中可以看到,nodeValue就是您要查找的内容。你可以访问它

$a->nodeValue;

Depending on the nodeType property this will return the text value.

根据nodeType属性,这将返回文本值。

You find this and all other public accessible properties and methods here:

您可以在此处找到此以及所有其他公共可访问属性和方法:

http://www.php.net/manual/de/class.domnode.php

http://www.php.net/manual/de/class.domnode.php

#1


0  

As you can see from the dump of the node object, the nodeValue is what you are looking for. You access it with

从节点对象的转储中可以看到,nodeValue就是您要查找的内容。你可以访问它

$a->nodeValue;

Depending on the nodeType property this will return the text value.

根据nodeType属性,这将返回文本值。

You find this and all other public accessible properties and methods here:

您可以在此处找到此以及所有其他公共可访问属性和方法:

http://www.php.net/manual/de/class.domnode.php

http://www.php.net/manual/de/class.domnode.php