Home > Net >  How to successfully modify in PHP the DOM of the Document of a CSS class in my case?
How to successfully modify in PHP the DOM of the Document of a CSS class in my case?

Time:06-11

I am trying to modify (replace) with DomDocument the attribute of the new CSS class of the a tag (framed on the following screenshot in green) which I have checked well with the function stripos and try to replace its href attribute (i.e. replace the href attribute of the a tag with new CSS class) with str_ireplace:

enter image description here

My following PHP Code looks correct but doesn't work at all:

libxml_use_internal_errors(true);
$parser = new DOMDocument();
$parser->loadHTMLFile("https://fr.wikipedia.org/wiki/Alibaba_Group");
$get_a_tags = $parser->getElementsByTagName("a");
foreach ($get_a_tags as $get_a_tag) {
                if (stripos($get_a_tag->getAttribute('class'), "new") !== false) {
                    $get_href_in_a_infobox = $get_a_tag->getAttribute('href');
                    $term = $get_a_tag->nodeValue;
                    $urlSearch = BASE_PATH."search.php?term=$term&type=sites";
                    // var_dump($urlSearch."<br><br>");
                    $wikipediaInfoboxTable = str_ireplace($get_href_in_a_infobox, $urlSearch, $wikipediaInfoboxTable);
                }
            }

So, how to succeed in replacing the value of the href attribute of all the a tags having the new CSS class by the value of the $urlSearch variable knowing that $wikipediaInfoboxTable contains the entire table of the infobox in which I would like to make my replacement ???

Thank you please help me.

CodePudding user response:

Since you're using DomDocument you can try using the setAttribute method to change the href value:

foreach ($get_a_tags as $get_a_tag) {
    //...
    $get_a_tag->setAttribute('href', $urlSearch);
}
$newHtml = $parser->saveHTML();
  • Related