问题
How can I do the following edits to an XML file in PHP. I basically want to keep some elements and write those elements to a new XML file.
So, I know how to open the new file and prepare it for writing and then open the XML file and iterate through it line by line:
$lines = fopen("file.xml", "r");
$new = fopen("newFile.xml", "w");
foreach($lines as $line){
/* operations on each line here */
}
I don't want to do operations on each line, but on certain elements in the file.xml.
What I need to do is for each <doc> element (everything in between <doc> and </doc>):
echo "<doc>"and break to a new line in $new.- write everything in between
<title>and</title>including the tags to $new. - write everything in between
<url>and</url>including the tags to $new. - write everything in between
<abstract>and<abstract>including the tags to $new. echo "</doc>"and break to a new line.
and then move on to the next <doc> </doc> block.
I would greatly appreciate all and any help in learning how to do the above.
回答1:
Try doing something with the simplexml library like in the following example:
$xml = simplexml_load_file("file.xml"); //load file as SimpleXML object
$newXml = SimpleXMLElement(); // create new SimpleXML object
foreach ($xml->doc as $d){ // change "$xml->doc" to the path to doc in your file
$doc = $newXml->addChild("doc"); // add <doc></doc>
$doc->addChild("title", (string)$d->title); //add title child within doc
$doc->addChild("url", (string)$d->url); //add url child within doc
$doc->addChild("abstract", (string)$d->abstract); //add abstract child within doc
}
$new = fopen("newFile.xml", "w"); // open new file
fwrite($new, $newXml->asXML()); //write XML to new file using asXML method
fclose($new); // close the new file
Hope this helps. You can find the full documentation of simplexml here: http://php.net/simplexml.examples-basic and there are many more concrete questions and answers here on Stackoverflow: simplexml
回答2:
In PHP you have two easy options for working with XML files. (There are others)
The first has already been pointed out: SimpleXML
The second option is DOM - Document Object Model
To make life even easier, you can search an XML file with XPath
$doc = new DOMDocument;
$doc->load('myXMLFile.xml');
$xPath = new DOMXPath($doc);
// Give me all doc elements inside the XML
$docElements = $xPath->query('doc');
foreach ($docElements as $docElement) {
// Work your magic here!
}
来源:https://stackoverflow.com/questions/17331495/parse-and-edit-xml-file-in-php