Parse and edit XML file in PHP [duplicate]

孤人 提交于 2019-12-11 23:51:40

问题


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>):

  1. echo "<doc>" and break to a new line in $new.
  2. write everything in between <title> and </title> including the tags to $new.
  3. write everything in between <url> and </url> including the tags to $new.
  4. write everything in between <abstract> and <abstract> including the tags to $new.
  5. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!