Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/symfony/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
DomCrawler Symfony:如何从不包括子节点的节点获取内容?_Symfony_Web Crawler - Fatal编程技术网

DomCrawler Symfony:如何从不包括子节点的节点获取内容?

DomCrawler Symfony:如何从不包括子节点的节点获取内容?,symfony,web-crawler,Symfony,Web Crawler,假设我有这样一个html页面: <html> <head></head> <body> Hello World! <div> my other content </div> </body> </html> 但这显然会产生一个错误: InvalidArgumentException: "The current node list is empty" 不知道这是否更容易,但您可以使用X

假设我有这样一个html页面:

<html>
<head></head>
<body>
    Hello World!
    <div> my other content </div>
</body>
</html>
但这显然会产生一个错误:

InvalidArgumentException: "The current node list is empty"

不知道这是否更容易,但您可以使用XPath提取文本节点内容:

$crawler->filterXPath('//body/text()')->text();
结果将是一个
字符串
,包含
Hello World
和文本前后的空格,直到第一个标记。因此,如果只需要文本本身,可以修剪值:

$helloWorld = trim($crawler->filterXPath('//body/text()')->text());
但是,如果正文中有多个文本节点,则这将适用于您的情况,例如:

<html>
<head></head>
<body>
    Hello World!
    <div> my other content </div>
    Some other text
</body>
</html>
这将返回一个数组:

Array
(
    [0] =>
        Hello World!

    [1] =>
        Some other text

)
$crawler->filterXPath('//body/text()')->extract(['_text']));
Array
(
    [0] =>
        Hello World!

    [1] =>
        Some other text

)