I am attempting to read the results of the executed header.php/footer.php files as a string of html. Here’s the scenario:
There are pages in the site that are developed in a .net environment but they want to share common headers/footers across the entire domain. They wish to have WordPress be the repository for this code and any time there is an update have a PHP cURL call to a .net web service and feed it the new HTML for the header/footers.
I tried calling get_header() but that does not return a string (as I anticipated) so then I tried this test solution in functions.php:
function write_header() {
$header_content = file_get_contents(get_bloginfo('wpurl').'/index.php' );
$fp = fopen('c:header.txt', 'a+');
fwrite($fp, $header_content);//just testing the output, this will be a cURL call eventually.
fclose($fp);
}
add_action( 'wp_update_nav_menu', 'write_header' );
It seems to be a very heavy handed method of getting the HTML since I’ll have to do a lot of string manipulation to parse out the pieces I want. Is there a simpler way of doing this that I’m missing?
If
get_header()
outputs the header for you, try just wrapping it with anob_start()
andob_get_contents()
to extract the header to a string. You can then discard the output withob_end_clean()
. See the PHP output buffering documentation.There’s a couple ways you can approach this problem (both are a bit of kludge, but what isnt…). The first would be to create a template in your theme’s directory that will include only the header and footer calls — the body of the template can contain a delimiter string like an html comment, e.g.
<!-- SPLIT HERE -->
.Request the page through CURL into an output buffer, capturing the resulting response, which you can split into it’s component parts using the above delimiter. That will give you your header and footer, complete with the fully rendered tags in the header for css,js, etc. It’s not pretty, but it does the job.
The second approach would be an adaptation of the first, which, rather than you doing the splitting, have your .net team take care of it on their end if possible.
UPDATE
Okay, so there’s actually a third option, which I completely forgot about, and that’s to use one of WP’s features:
wp_remote_get()
http://codex.wordpress.org/Function_API/wp_remote_getThis is what you should get back (excerpted from the API docs):
All you’d have to do is pass the URL to a page that’s using the template I mentioned above, then handle response from
wp_remote_get()
; extract the html content form[body]
and do your string splitting. Pretty much what you want.Further reading:
wp_remote_retrieve_body()
http://codex.wordpress.org/Function_API/wp_remote_retrieve_body