How to replace all ul and li tag with div using PH

2019-07-20 12:44发布

问题:

Ok, I want to create a "website mobilizer" by using PHP Simple HTML DOM Parser. In the present phase, I want to-

  1. change all 'ul' and 'li' tag to 'div' tag and
  2. change all 'table' elements (e.g. table,tr,td,th) to div. I tried an workaround for the first problem in following way:

.

$html=new new simple_html_dom();
$html>load_file($sourceurl);

$div="div";
foreach ($html->find('ul') as $element) {  
 $element=$div;
 }

It does seem dull, but I'm not being able to find any other solution. I am discouraged for using preg_match, though I don't know if it can give me the desired output. Any help will be appreciated.

回答1:

It is possible:

$html=new new simple_html_dom();
    $html>load_file($sourceurl);

    foreach ($html->find('ul') as $element) {  
     $element->innertext = "<div>".$element->innertext."</div>";     
    }

Of course you can do the same with table. More in doucmetation: Simple HTML DOM Parser Manual



回答2:

$html=new new simple_html_dom();
$html>load_file($sourceurl);

$replace="ul,li,table,tr,td,th";  
foreach($html->find($replace) as $key=>$element){
    $html->find($replace,$key)->outertext="<div>".$element->innertext."</div>"
}

this replaces all the elements from $replace array to <div> in $html DOM without changing the contents of those tags. Everything is stored in $html DOM.

As you can see you cant use $element to change anything in $html, even using $element as a reference, so you have to access $html directly.