0

How can I add a code before or after a spesific element using PHP Simple HTML DOM?

For example: before

<head> add

<style> .someclass { text-align:center } </style>

output shold be:

....
<style> .someclass { text-align:center } </style>
<head>
.....

and inside some spesific div how can I add a code for example:

before parsing:

<div class="mydiv">...some original staff..</div>

after parsing should be:

<div class="mydiv"><span>my staff</span>...some original staff..</div>

I coldn't figure out. Just I achieved to replace or remove elements. Also woould appreciate if you can suggest alternative method to do this.

3
  • The output is just string? What's wrong with using str_replace? Commented Dec 12, 2013 at 10:48
  • but ouptput is coming from another url $html = file_get_html('http://someurl.com/some.php?id=3965'); Commented Dec 12, 2013 at 10:57
  • 1
    just to illustrate the problem, can I just str_replace('class="mydiv">', 'class="mydiv"><span>my staff</span>', $html)? Commented Dec 12, 2013 at 11:02

1 Answer 1

2

Thank you Andrew it worked. I was focused to do it with simple html dom that I didn't think that there is simpler way to do that. this is how to inject element with simple htmldom

<?
include('simple_html_dom.php');
$html = file_get_html('http://someurl.com');     
$inject  = '<style> .someclass { text-align:center } </style>';
$html->find('head', 0)->innertext = $inject.$html->find('head', 0)->innertext;
echo $html;
?>

and this is your suggestion.

<?
include('simple_html_dom.php');
$html = file_get_html('http://someurl.com');     
$html = str_replace('</head>', '<style> .someclass { text-align:center } </style></head>', $html);
echo $html;
?>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.