关注此帖Saving form data to an existing XML-file using PHP
我想知道如何将多个变量保存到xml文件中。使用描述的方法,我只能保存最后一个。
我发现了一种按我想要的方式工作
$xml="\n\t\t<Bares>\n\t\t";
{
while ($stmt->fetch()){
$xml .="<Bar>\n\t\t";
$xml .= "<nome>".$nome."</nome>\n\t\t";
$xml .= "<morada>".$morada."</morada>\n\t\t";
$xml .= "<nif>".$nif."</nif>\n\t\t";
$xml .= "<telefone>".$telefone."</telefone>\n\t\t";
$xml .= "<email>".$email."</email>\n\t\t";
$xml .= "<imgid>".$imgid."</imgid>\n\t\t";
$xml.="</Bar>\n\t";
}
$xml.="</Bares>\n\r";
$doc = new DOMDocument('1.0');
$doc->formatOutput = true;
$doc->preserveWhiteSpace = true;
$doc->loadXML($xml, LIBXML_NOBLANKS);
$doc->save('dados.xml');
但我希望能够编辑xml标头标签(xml版本=&#34; 1.0&#34;?),我不能这样做
答案 0 :(得分:0)
再次考虑使用DOMDocument()方法,而不是使用字符串连接构建XML。使用PHP的信息手册,下面显示了如何添加Document Type Declaration (DTD)和XSLT processing line:
// Create an instance of the DOMImplementation class
$imp = new DOMImplementation;
// Create a DOMDocumentType instance
$dtd = $imp->createDocumentType('graph', '', 'graph.dtd');
// Create a DOMDocument instance
$doc = $imp->createDocument();
// Set other properties
$doc->encoding = 'UTF-8'; $doc->standalone = true;
$doc->formatOutput = true; $doc->preserveWhiteSpace = true;
// Create an XSLT adding processing line
$xslt = $doc->createProcessingInstruction('xml-stylesheet',
'type="text/xsl" href="base.xsl"');
// Append XSLT instruction to the doc
$doc->appendChild($xslt);
// Append DTD to the doc
$doc->appendChild($dtd);
// Create root
$root = $doc->appendChild($doc->createElement('Bares'));
// Iteratively append the elements (with values)
while ($stmt->fetch()){
$barNode = $root->appendChild($doc->createElement('bare'));
$nomeNode = $barNode->appendChild($doc->createElement('nom', $nome));
$moradaNode = $barNode->appendChild($doc->createElement('morada', $morada));
$nifNode = $barNode->appendChild($doc->createElement('nif', $nif));
$telefoneNode = $barNode->appendChild($doc->createElement('telefone', $telefone));
$emailNode = $barNode->appendChild($doc->createElement('email', $email));
$imgidNode = $barNode->appendChild($doc->createElement('imgid', $imgid));
}
$doc->save('dados.xml');