Because a PHP code page produces and outputs a HTML document, the html/head/body tags are just data as far as PHP is concerned. Any block of PHP code goes wherever it logically needs to be to produce the content you want.
About the only real constraint is, any logic you have that causes a header to be sent to the browser must occur before any actual content is sent to the browser.
In the following, the PHP code is
not in the <body> -
The line of php code in the above example is just one line of the overall HTML document. It just happens to be after the first 7 lines of in-line HTML.
In the above example, PHP code could just as easily echo all the lines shown, without having any in-line HTML that is outside of the <?php ?> tags.
You could also have a block of PHP echoing the title - echo "<title>Some Title</title>"; or you could have a block of php producing and echoing CSS or some javascript.
Think in terms of the overall document that is formed and sent to the browser.