Xml添加/添加新节点php



我正在尝试更新和添加节点到xml文件。目前,我可以用我的新节点创建和覆盖文件,但是我需要做的是将新节点添加到现有文件(.xml)中,然后我就筋疲力尽了。我是新的php(我已经尝试了这个网站上的所有代码,这是我目前的代码不能添加在这里…请帮助

$doc = new DOMDocument; 
// Load the XML 
///$doc->loadXML("<root/>"); 
//---- ///$xml = new Document; 
///$xml ->loadXML($xml); 
//$xml = simplexml_load_file("pole.xml"); 
$title = $_POST["title"]; 
$xml = <<<XML <item> <title>$title</title> </item> XML; 
$xml = new Document; 
$xml ->loadXML($xml); 
$xml ->appendXML($xml); 
$xml = new SimpleXMLElement($xml); 
echo $xml->saveXML('pole.xml'); 

我不能提供使用SimpleXML的建议,但由于上面确实尝试使用DOMDocument,也许下面的简单示例将有用。

$filename='pole.xml';
# Stage 1
# -------

// Create an instance of DOMDocument and then
// generate whatever XML you need using DOMDocument
// and save.
libxml_use_internal_errors( true );
$dom=new DOMDocument('1.0','utf-8');
$dom->formatOutput=true;
$dom->preserveWhiteSpace=true;

$root=$dom->createElement('Root');
$dom->appendChild( $root );
$item=$dom->createElement('Item');
$title=$dom->createElement('title','Hello World');

$item->appendChild( $title );
$root->appendChild( $item );

$dom->save( $filename );
$dom=null;

生成以下XML:

<?xml version="1.0" encoding="utf-8"?>
<Root>
<Item>
<title>Hello World</title>
</Item>
</Root>

然后修改您创建或下载的XML文件等:

# Stage 2
# -------

// A new instance of DOMDocument is NOT strictly necessary here
// if you are continuing to work with the generated XML but for the purposes
// of this example assume stage 1 and stage 2 are done in isolation.

// Find the ROOT node of the document and then add some more data...
// This simply adds two new simple nodes that have various attributes
// but could be considerably more complex in structure.


$dom=new DOMDocument;
$dom->formatOutput=true;
$dom->preserveWhiteSpace=false;
$dom->load( $filename );
# Find the Root node... !!important!!
$root=$dom->getElementsByTagName('Root')->item(0);
# add a new node
$item=$dom->createElement('Banana','Adored by monkeys');
$attributes=array(
'Origin'    =>  'Central America',
'Type'      =>  'Berry',
'Genus'     =>  'Musa'
);
foreach( $attributes as $attr => $value ){
$attr=$dom->createAttribute( $attr );
$attr->value=$value;
$item->appendChild( $attr );
}
#ensure that you add the new node to the dom
$root->appendChild( $item );


#new node
$item=$dom->createElement('Monkey','Enemies of Bananas');
$attributes=array(
'Phylum'    =>  'Chordata',
'Class'     =>  'Mammalia',
'Order'     =>  'Primates'
);
foreach( $attributes as $attr => $value ){
$attr=$dom->createAttribute( $attr );
$attr->value=$value;
$item->appendChild( $attr );
}
$root->appendChild( $item );


$dom->save( $filename );
$dom=null;

这会修改XML文件并产生以下结果:

<?xml version="1.0" encoding="utf-8"?>
<Root>
<Item>
<title>Hello World</title>
</Item>
<Banana Origin="Central America" Type="Berry" Genus="Musa">Adored by monkeys</Banana>
<Monkey Phylum="Chordata" Class="Mammalia" Order="Primates">Enemies of Bananas</Monkey>
</Root>

最新更新