2

I'm pretty new to PHP, so i try to use Simple HTML DOM Parser to get the information i need from a website. here is the sample node:

<div>
    <h1>Hello</h1>
    <figure id="XXX">
        <div class="abc">ABC</div>
        <div class="qwe">QWE</div>
        <div class="zxc">ZXC</div>
    </figure>
</div>

$element contain above node. What i need to get is the "QWE", so i try:

$name = $element->find('figure[id=XXX]')->children(1)->innertext;

but now the problem: Fatal error: Call to a member function children() on a non-object , that is no problem if i stop at find('figure[id=XXX]'), but it return array and i can't get the exact information.

Any solution? Please help, thanks in advance.

crossRT
  • 616
  • 4
  • 12
  • 26

2 Answers2

3

There you go:

 $str = '<div>
            <h1>Hello</h1>
            <figure id="XXX">
            <div class="abc">ABC</div>
            <div class="qwe">QWE</div>
            <div class="zxc">ZXC</div>
            </figure>
        </div>';

$html = str_get_html($str);

$str = $html->find('figure[id=XXX]',0)->children(1)->plaintext;

echo($str);

find returns elements and you need single element so set index 0 (the first one) at the second parameter in find

Adidi
  • 5,097
  • 4
  • 23
  • 30
  • Thanks @Adidi! I figure this problem almost 1 hour, but you solve it in few second. Thank you so much. Actually what does the find(string $selector [,int $index]) index mean for? – crossRT Apr 22 '13 at 12:35
  • what element to return from the collection/list - find returns always a list and by setting the `$index` you telling it you want a specific element in that index from the list - so if you choose something with id its mandatory to be the first element - meaning index zero – Adidi Apr 22 '13 at 12:39
  • Sorry @Adidi, 1 more question, any solution to catch when the tag not found? for example, assume
    is not exist in current element?
    – crossRT Apr 22 '13 at 13:41
  • It's ok - glad to help - always ask on the return value - whether it return list(array) or single element - if it can't find it it will return null or empty array so you can do: `$els = $html->find('something'); if($els){exits}else{not exits};` – Adidi Apr 22 '13 at 13:58
  • okay, get it. But my case now, I use $element->find('figure[id]') to get all tag, then only use getAttribute('id') to do something i want. once again, thank you very much. =) – crossRT Apr 22 '13 at 15:56
0

It's better to do:

$html->find('figure#XXX > *[2]',0)->plaintext;
pguardiario
  • 53,827
  • 19
  • 119
  • 159