PHP and XML

Use DOM
&lt?php

//Creates XML string and XML document using the DOM
$dom = new DomDocument('1.0');

//add root - <books>
$books = $dom->appendChild($dom->createElement('books'));

//add <book> element to <books>
$book = $books->appendChild($dom->createElement('book'));

//add <title> element to <book>
$title = $book->appendChild($dom->createElement('title'));

//add <title> text node element to <title>
$title->appendChild($dom->createTextNode('Great American
Novel'));

//generate xml
$dom->formatOutput = true; // set the formatOutput attribute of
domDocument to true
// save XML as string or file
$test1 = $dom->saveXML(); // put string in test1
$dom -> save('test1.xml'); // save as file
?&gt

Use SimpleXML

$sxe = simplexml_load_string('<books><book><title>Great American
Novel</title></book></books>');

if ($sxe === false) {
echo 'Error while parsing the document';
exit;
}

$dom_sxe = dom_import_simplexml($sxe);
if (!$dom_sxe) {
echo 'Error while converting XML';
exit;
}

$dom = new DOMDocument('1.0');
$dom_sxe = $dom->importNode($dom_sxe, true);
$dom_sxe = $dom->appendChild($dom_sxe);

echo $dom->saveXML('test2.xml');
?&gt

DOM SimpleXML
$dom = new domDocument;
$dom->loadXML('<books><book><title>Great American
Novel</title></book></books>');
if (!$dom) {
echo 'Error while parsing the document';
exit;
}

$s = simplexml_import_dom($dom);

echo $s->book[0]->title; // Great American Novel
?&gt

你可能感兴趣的:(xml,PHP)