I need to extract the text in After divs using Simple HTML Dom PHP library. I have tried next_sibling() to get text but it's dont work.

<div class="one">one<div>
<div class="data">mydata</div>
get this text
<div class="two">two</div>

My code:

$res = $div->find('div[class="data]',0);
if($res->plaintext == 'mydata'){
    echo $res->next_sibling()->plaintext  ;
}

3 Answers

0
Emma On Best Solutions

Welcome!

It seems you want to parse an HTML using DOMDocument method. If that might be the case, you might instantiate a new object, maybe similar to:

$dir = '<div class="one">one<div>
<div class="data">mydata</div>
get this text
<div class="two">two</div>';

$dom = new DOMDocument();
$dom->loadHTML($dir);
$xpath = new DOMXpath($dom);

$res = $xpath->document->documentElement->textContent;

$textNodes = explode(PHP_EOL, $res);
foreach ($textNodes as $key => $text) {
    if ($text == 'mydata') {
        echo $textNodes[$key + 1];
        break;
    }
}

Then, you can do the rest of anything that you wish to do with document.

Output:

get this text

Document

If you var_dump($xpath->document->documentElement);, you can find out how you might want to use attributes of documentElement object:

twoobject(DOMElement)#3 (18) {
  ["tagName"]=>
  string(4) "html"
  ["schemaTypeInfo"]=>
  NULL
  ["nodeName"]=>
  string(4) "html"
  ["nodeValue"]=>
  string(20) "one
mydata
two
three"
  ["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"]=>
  NULL
  ["attributes"]=>
  string(22) "(object value omitted)"
  ["ownerDocument"]=>
  string(22) "(object value omitted)"
  ["namespaceURI"]=>
  NULL
  ["prefix"]=>
  string(0) ""
  ["localName"]=>
  string(4) "html"
  ["baseURI"]=>
  NULL
  ["textContent"]=>
  string(20) "one
mydata
two
three"
}
0
Mohsen Shakibafar On

It's look you need to change your html content with Simple_html_dom.

I find one solution for you that return get this text.

$res = $html->find('div[class="data"]',0);
    if($res->plaintext == 'mydata'){
        $res->parent()->first_child()->outertext ='';
        $res->parent()->last_child()->outertext ='';
        echo $res->parent()->innertext;
    }

after i find div with class='data' i changed the html content and remove first and last element , so the plain text that you want remains.

0
Abanoub Istfanous On

I recommend you to use JQuery for this it is very easy you can type

<script>
$(".data").append("whatever you want");
</script>

EXPLAIN : $ in jquery is global select to select element you put .class-name insinde $(" ") then use method appen() to add elemnts