Search code examples
htmldomparser

Parsing HTML and change anchor only works for the first anchor on each span


I want to replace every anchor on HTML and have use this code but it seems there something missing:

foreach($html->find('div') as $dict) {
    $dict->find('SPAN', 0)->find('A', 0)->href = "link.php?" . $dict->find('SPAN', 0)->find('A', 0)->innertext;
}

The HTML structure is like:

<DIV>
    <SPAN> 
        Text text text <A HREF="link1.php">LINK_A</a>, 
        text text <A HREF="link1.php">LINK_B</a>.
    </SPAN>
</DIV>
...

What I supposed to do with that code is to change all of the anchor on the html become:

<DIV>
    <SPAN> 
        Text text text <A HREF="link.php?LINK_A">LINK_A</a>, 
        text text <A HREF="link.php?LINK_B">LINK_B</a>.
    </SPAN>
</DIV>
...

But the code only works for the first anchor on each span, like:

<DIV>
    <SPAN> 
        Text text text <A HREF="link.php?LINK_A">LINK_A</a>, 
        text text <A HREF="link1.php">LINK_B</a>.
    </SPAN>
</DIV>
...

I tried to modify the code become:

foreach($html->find('div') as $dict) {
    foreach($dict->find('SPAN', 0)->find('A', 0) as $anchor) {
        $anchor->href = "link.php?" . $anchor->innertext;
    }
}

But it get worst. How can I do that? Thanks.


Solution

  • You are declaring that you want to find the 1st span only here...

    $dict->find('SPAN', 0)
    // The 0 means the first one only I expect