构建一个PHP XML字符串(使用addChild())并将其加载到其他页面上


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

我用以下代码创建了一个XML字符串:

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

然后我将这个php文件包含到另一个php页面中,并使用addChild()来插入一个新节点。

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

但是当我试图添加另一个"product"节点时(通过转到另一个页面),XML字符串将不保留第一个"product"节点。

我如何在会话期间以及登陆到其他页面时保留带有添加节点的XML字符串?我必须创建一种会话变量吗?还是不变?或类?或者是否有更简单的方法通过一批页面处理XML ?

如果你转到一个新页面,整个过程将从头开始。如果你想操纵同样的xml,您必须以某种方式将它(作为字符串或作为对象)从一个页面传递到另一个页面。

这里最简单的可能是将它存储在会话变量 中。

您的include可能看起来像s:

// 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;
}

在你使用这个包含的所有页面中,你会做

// get the xml from session
$product = $_SESSION['mysimplexml'];
// manipulate xml code code here
// store back into session
$_SESSION['mysimplexml'] = $product;