在PHP中解析和编辑XML文件 [英] Parse and edit XML file in PHP
问题描述
如何对PHP中的XML文件进行以下编辑.我基本上想保留一些元素并将这些元素写入新的XML文件.
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.
因此,我知道如何打开新文件并为编写做准备,然后打开XML文件并逐行进行遍历:
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 */
}
我不想对每一行进行操作,而是对file.xml中的某些元素进行操作.
I don't want to do operations on each line, but on certain elements in the file.xml.
我需要为每个<doc>
元素(<doc>
和</doc>
之间的所有元素):
What I need to do is for each <doc>
element (everything in between <doc>
and </doc>
):
-
echo "<doc>"
并在$ new中换行. - 编写介于
<title>
和</title>
之间的所有内容,包括$ new的标签. - 编写介于
<url>
和</url>
之间的所有内容,包括$ new的标签. - 编写
<abstract>
和<abstract>
之间的所有内容,包括$ new的标签. -
echo "</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.
,然后继续下一个<doc>
</doc>
块.
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.
推荐答案
尝试使用 simplexml库 如下例所示:
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
希望这会有所帮助.您可以在此处找到simplexml的完整文档: http://php.net/simplexml.examples-basic,而Stackoverflow上还有更多具体的问题和答案: simplexml
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
这篇关于在PHP中解析和编辑XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!