简体   繁体   中英

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>';

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 .

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
} ?>

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
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM