Handling the processed output

There are two ways to deal with the output of xslt_process(). One way is to use the optional fourth parameter that allows you to specify the name of a file you wish to save the processed content to. If you do not provide this parameter, or it is NULL, then xslt_process() returns the processed content via its return value.

The option you choose is obviously dependent on your plans for the output. Usually you will probably want to ignore the fourth parameter (or supply NULL) in order to get the content back in the function return value. This is done by capturing the return value in a variable, or by passing it straight to an print statement. Using our previous example, here is what that would look like. Save it as xslt_test.php:

    $xslt_result = xslt_process($xsltproc,'/path/to/input.xml','/path/to/input.xsl');

    print $xslt_result;

The difference here is that we capture the return value of xslt_process() in $xslt_result, which we then print out later on the script. While it is just as good in this situation to replace the "$xslt_result = " line with just print, you may wish to replace the dots between the xslt_process() and the printing out of the results with more PHP code. Note that there is no need to add an <HTML> tag in the PHP output because XSL is designed to add <HTML> and other basic tags if it matches a root element.

Go ahead and run the xslt_test.php script. If everything has gone as planned, you should be see your formatted XML returned. Also, take a look at the source of the page and note that it is all nicely-formatted XHTML.


Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Making XSL work for its money >>

Previous chapter: Adding PHP to the mix

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.