#native_company# #native_desc#

Using PHP and XML with Apache Cocoon Page 3

By Darren Beale
on July 30, 2000

Stage 2) Bring on the PHP

Ok, so this is all well and good, but It??s static mark-up, I want to use PHP to generate the XML dynamically, so lets look at the next example, phpbuilder.php:



    I want to print out a greeting to a number of 

    countries, not just the World, so in no particular order


$countries = array (



"Sweden""Japan""China""New Zealand""Australia"


//Now open up a file on the server called dynamic-phpbuilder.xml

$handle fopen("./dynamic-phpbuilder.xml","w");


    Now we build up a string that we can save out to our file, notice that the 

    "<?" tags have been separated so we don't confuse the PHP interpreter.


$tofile "<" "?" "xml version="1.0"" "?" ">n";

$tofile .= "<" "?" "xml-stylesheet href="dynamic-phpbuilder.xsl" type="text/xsl"" "?" ">n";

$tofile .= "<" "?" "cocoon-process type="xslt"" "?" ">nn";

$tofile .= "<phpbuilder>n";

$tofile .= "t<heading>This is a Dynamically Generated XML that has been Transformed using XSLT</heading>n";


    We now do a very simple loop and output our 

    greeting to all the countries in our example array:


for ($x=0;$x<sizeof($countries);$x++) {

$tofile .= "t<message>n";

$tofile .= "tt<greeting>" $countries[$x] . "</greeting>n";

$tofile .= "t</message>n";


$tofile .= "</phpbuilder>n";

//Write the string to our file and close the handle



//Finally we redirect to the newly created dynamic-phpbuilder.xml file.

header("Location: dynamic-phpbuilder.xml");