简体   繁体   中英

php simple html dom, parse some html between 2 html tag by id

I have a big tree, and I tried to parse some html between 2 html tag by id (between h2#ftc to h2#ftd) use simple html dom, how to do it in a right way? my code get an empty data. Thanks.

require ("simple_html_dom.php");
$result=<<<EOT
<ul>
    <h2 id="fta">tree1</h2>
        <li>nod a</li>
        <li>nod b</li>
        <li>nod c</li>
    <h2 id="ftb">tree2</h2>
        <li>nod d</li>
        <li>nod e</li>
        <li>nod f</li>
    <h2 id="ftc">tree3</h2>
        <li>nod g</li>
        <li>nod h</li>
    <h2 id="ftd">tree4</h2>
        <li>nod i</li>
        <li>nod j</li>
        <li>nod k</li>
        <li>nod l</li>
</ul>
EOT;

$html = str_get_html($result);

foreach($html->find("ul") as $st) {
    if($st->find("h2[id=ftc]")){continue;}
    echo $st;
    if($st->find("h2[id=ftd]")){break;}
}

And I want only output:

<h2 id="ftc">tree3</h2>
<li>nod g</li>
<li>nod h</li>

You'd be far better off using the DOM classes provided with PHP instead of attempting to roll your own solution.

$doc = new DOMDocument ();
$doc -> load ($result);
if ($list = $dom -> getElementById ('fta'))
{
    // Do your processing in here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM