MrMacvos
MrMacvos

Reputation: 103

Include CSS and JS in PHP based on condition

Is there a way to search the PHP content body while it is being parsed by PHP for certain keywords, so I can include CSS and JS files based on the presence of those keywords before the page is being served?

If PHP would have a variable like $_CONTENT_BODY where it outputs the parsed page into, then I could search for keywords like in this example:

if(stripos($_CONTENT_BODY, 'usetinymce') !== false)) echo '<script type="text/javascript" src="http://a.host.com/js/tinymce/jscripts/tiny_mce/tiny_mce.js"></script>';

Upvotes: 0

Views: 225

Answers (4)

Kustolovic
Kustolovic

Reputation: 172

You can include another php file and get the results with ob_start/ob_get_clean()

ob_start();
include 'myfile.php'; 
$_CONTENT_BODY = ob_get_clean();

But you will encounters some problems, like white pages on some php errors. It is better to build your app more logicaly instead of doing some dirty search & replace.

Upvotes: 0

Nigel Ren
Nigel Ren

Reputation: 57121

You could use ob_start(); and $text = ob_get_contents();. Just make sure that you process these properly, check out http://php.net/manual/en/book.outcontrol.php.

Upvotes: 1

Bernhard
Bernhard

Reputation: 1870

You can assemble a Variable which you can search and output at the End.

$_CONTENT_BODY  = 'here ';
$_CONTENT_BODY .= 'is some ';
$_CONTENT_BODY .= 'content.';

if(stripos($_CONTENT_BODY, 'some')){
 // do whatever you like
}

Upvotes: 0

Giorgio Catenacci
Giorgio Catenacci

Reputation: 199

You can get the page itself and parse it.

<?php   
if (!isset($_GET['doNotCallMeAgain']) || $_GET['doNotCallMeAgain'] !== 1) {
    $urltothisfile = 'urltothefilehimself'+'?doNotCallMeAgain=1';
    $result = file_get_contents ($urltothisfile); //in $result you will get your page as html and you can search in it
} ?>

Upvotes: 0

Related Questions