Building an PHP XML string (with addChild()) and loading it on other pages

I created an XML string with the following code:

$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<product_list>
</product_list>
XML;

Then I included this php file into another php page, and work with the addChild() to insert a new node.

include 'xml.php';
$product = new SimpleXMLElement($xmlstr);
$newprod = $product->addChild("product");
$newprod->addChild("reference", $xml->product[$ref_prod]->reference);
...

But when I'm trying to add another "product" node (by going to another page), the XML string will not keep the first "product" node.

How can I keep the XML string with the added nodes during my session, and by landing to other pages? Do I have to create a kind of session variable? Or constant? Or class? Or is there an easier way to work with XML through a batch of pages?

If you go to a new page, the whole process starts all over again. If you want to manipulate the same xml, you will have to pass it (as a string or as an object) from one page to the other somehow.

The easiets here is most probably storing it in a session variable

Your include could look like s this:

// make the sessionaccessible
session_start();

// create xml if it does not exist
if(!$_SESSION['mysimplexml'])
{
   // create the string 
   $xmlstr = <<<XML
             <?xml version='1.0' standalone='yes'?>
             <product_list>
             </product_list>
             XML;   

   // parse it into the simplexml object
   $product = new SimpleXMLElement($xmlstr);

   // store in the session variable
   $_SESSION['mysimplexml'] = $product;
}

In all the pages you use this includeyou would do

// get the xml from session
$product = $_SESSION['mysimplexml'];

// manipulate xml code code here

// store back into session
$_SESSION['mysimplexml'] = $product;