Search code examples
phphtmlcsshead

How to append to <head> with PHP in the middle of the page?


I have an HTML "chunk" of code with HTML and JS in it so I could easily include it with PHP. I also want it to have CSS styling but according to standards you are not "allowed" to do that - while it works it makes the page invalid. CSS is only allowed in <head> and not in the middle of the page (not untill HTML5.2 at least). So I thought about appending similarly named but separate .css file in the head, but with PHP and not JS (for performance sake)

<head>
<!-- PHP needs to include button.css here AFTER $App->INC("button"); has been called -->
</head>

<body>
<?php
$App->INC("button");
//This basically does 'require_once("button")';
//What do I need to add to the INC method to include css file in the head?
//Similar to $("head").append() but with PHP
?>
</body>

css file with the same name should be added to a <head> section.

PS: This may seem as a design flaw and may as well be but here is the thought behind this.

  1. I have a piece of code that when included in the right place of the body generates a "loading screen" (or other UI elements that can't/shouldn't be nested anywhere else but in the <body> of the website.
  2. It's got styling in a separate file
  3. I send it to other user
  4. They include it with a method of an "App" class which only does two things: includes the file itself and css file nearby
  5. Then they only use 1 line of code to put it where they want it and not in 2-3 other places so the code is more manageable

Example:

Structure


Solution

  • You may try this:

    <?php
    ob_start();
    $App->INC("button");
    $button = ob_get_clean();
    ?>
    <head>
    <!-- Do your inclue here -->
    </head>
    
    <body>
    <?= $button ?>
    </body>
    

    You can put the ob_start() / ob_get_clean() stuff inside button.php and return the content via your INC() method. Then you can save the content directly into $button like this: $button = $App->INC("button");.

    But your example looks like a design problem. However I hope this will do the trick.


    This could be a possible redesign:

    <?php
    
    $App->loadModule('button'); // Loads the module, the module registers stylesheets and content.
    
    $App->loadModule('another_module'); // Load more modules ...
    
    <head>
    <?php $App->renderModuleStylesheets(); ?>
    </head>
    
    <body>
    <?php $App->renderModuleContent(); ?>
    </body>