0

Is there a similar way to select / perform DOM manipulation on the server-side (PHP) like the way jQuery works?

For example, if I wanted to modify content of each <pre class="raw">...</pre> elements inside of a post content, in jQuery you can easily capture them all with:

//In jQuery, this will obtain a collection of <PRE> elements with class "raw":
$("pre.raw").each( function(index,tag) {
    //Modify content of each PRE tags here...
    tag.innerHTML = tag.innerHTML.replace( ..., ... );
});

In PHP however, I'm trying to do this by adding a filter to "the_content", which will then do some string replacements only inside each of those <pre class="raw"> elements.

Does WordPress already have some built-in utility method to grab elements this way? Or does some 3rd party PHP script exists that will do this?

2 Answers 2

2

You may also take a look at phpQuery.

2
  • Unfortunately, it doesn't preserve the XML self-closing tags when parsing the string. Commented Nov 21, 2011 at 19:06
  • If this is a problem for you, you may consider Tidy with hide-endtags option Commented Nov 21, 2011 at 19:36
1

Answering to myself (and perhaps some other developers curious about this question), there is a PHP server-side script that can manipulate the DOM just like jQuery can:

http://simplehtmldom.sourceforge.net/index.htm

Althought the syntax isn't exactly the same (doesn't use the dollar $ sign as the jQuery object), the functionality works basically the same.

Example (taken from the above link):

$html = file_get_html('http://www.google.com/');

// Find all images 
foreach($html->find('img') as $element) 
       echo $element->src . '<br>';

// Find all links 
foreach($html->find('a') as $element) 
       echo $element->href . '<br>';
1
  • Replacing content in the $element->innertext property seems to discard all the new-line characters... NO GOOD! :( Commented Nov 21, 2011 at 19:07

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.