如何使用SimpleHTMLdom解析器解析没有类和没有id的p标记内容?

问题描述 投票:0回答:2

这是我要解析的html部分,以获取<p>中的文本:

<div class="container">
    <h2>title</h2>
    <div class="divIdontNeed"> hi </div>
    <p> I WANT THIS TEXT </p> <====== this is what i want
    <p> i don't want this one </p>
</div>

我做的是一个循环(因为上面的html在多个页面上,我希望所有这些都在数组$allTexts上):

foreach($html->find('div[class=container]')->find('p',0) as $text){

                    array_push($allTexts, $text->plaintext);
                }

当我这样做时,我得到一个错误说Fatal error: Call to a member function find() on array in /path/to/MyTextParser.php

谢谢你们

dom html-parsing simple-html-dom
2个回答
2
投票

您收到错误是因为第一个find()返回一个元素数组,而不仅仅是一个元素。

你需要对第一个find()的结果进行循环:

foreach($html->find('div[class=container]') as $element)
{
   foreach ($element->find('p',0) as $text){
   array_push($allTexts, $text->plaintext);
  }
 }

0
投票

你应该选择你想要的第n个元素。

$divObj=$html->find('div.container', 0);

echo $divObj->find('p', 0)->plaintext; //you are choosing only first p tag

echo $divObj->find('p', 1)->plaintext; //you are choosing only second p tag

如果你需要来自div的所有p元素的文本,你需要做foreach

要么

你可以选择它作为div的下一个兄弟与班级divIdontNeed

$divObj=$html->find('div.divIdontNeed', 0)->next_sibling();

echo $divObj->plaintext;
© www.soinside.com 2019 - 2024. All rights reserved.