My ultimate goal is to create a Word DOCX file from a generated HTML page. To do this, I used information from the question here from HTML <figure> and <figcaption> to Microsoft Word in which one of the answers mentioned a JavaScript plugin that would convert HTML to DOCX (jquery plugin by Mark Windsoll which converts HTML to Word).
The example in that answer and the plugin was used as a basis for the following code segment. In my program, I have previously created an HTML page (in a WordPress loop) (not just elements of the page, but an entire properly formatted HTML page) that contains the content I want to convert to DOCX. Also, I have loaded the needed JS and CSS needed by the "HTML to Word plugin".
The intent is to take the created HTML ($post_output
) and use the wordExport()
function (the JS that converts HTML to DOCX) to create the DOCX file, which I will then save.
<?php
$x = $post_output ; // $post_output contains an HTML page with doctype/head/body/etc that was generated by the loop
$dom = new DOMDocument;
libxml_use_internal_errors(false); // supress errors
$dom->loadHTML($x, LIBXML_NOERROR); // supress errors
?>
<script type="text/javascript">
$dom.wordExport();
</script>
The error I am getting is that the $dom
object in the script is not available, so the wordExport()
function is not called.
So I need a way to load the entire HTML string ($x
) into a JavaScript DOM object so that the wordExport()
function (which is the HTML to DOCX converter) will work. (added) the HTML 'string' is not a page in the browser, it's a generated 'HTML page source' assigned to a PHP string variable.)
Added The HTML string needs to be processed by the Word-to-DOCX jQuery plugin. Is this possible?
Don't be fooled by the fact that both JS and PHP have implementations of the DOM API; that doesn't mean that creating a PHP object will be any use to you for running a JS method. Remember that the JS runs in the browser, after all the PHP has finished, and all it sees is the output you've sent to the browser.
So what you need to do is
echo
that entire string of HTML, so you can pick it up in the JS code. You could make it into a JS string (basically, surround it with'
marks, but usingjson_encode
is a handy way of escaping any quotes etc in the content); or you could echo it as hidden content on the page. Then run it throughjQuery()
to get an appropriate object, and use your library.