[英]Merging XML documents with PHP
我有以下兩個xml文檔:
<outer>
<foo>
<foo-child name="fA" special="true">
content of fA
</foo-child>
<foo-child name="fB">
content of fB
</foo-child>
</foo>
<bar>
<bar-child name="bA">
content of bA
</bar-child>
<bar-child name="bB" special="true">
content of bB
</bar-child>
</foo>
</outer>
<outer>
<foo>
<foo-child name="fA">
newer and improved content of fA
</foo-child>
<foo-child name="fC">
content of fC
</foo-child>
</foo>
<bar>
<bar-child name="bA" really-special="true" />
<bar-child name="bB" special="false">
Despecialized content of bB
</bar-child>
</foo>
</outer>
我想將它們合並在一起,以使文檔2中的元素覆蓋文檔1中具有相同name
屬性的元素。 如果第二個文檔中不存在任何屬性或內容,則該屬性或內容將從第一個繼承。 所以:
<outer>
<foo>
<foo-child name="fA" special="true">
newer and improved content of fA
</foo-child>
<foo-child name="fB">
content of fB
</foo-child>
<foo-child name="fC">
content of fC
</foo-child>
</foo>
<bar>
<bar-child name="bA" really-special="true">
content of bA
</bar-child>
<bar-child name="bB">
Despecialized content of bB
</bar-child>
</foo>
</outer>
我的意圖是使用PHP在服務器端進行此操作。
但是,我不確定這是DomDocument
還是SimpleXML的工作。 我也沒有真正使用過,並且一直在想“我希望有jQuery”。
有解決這個問題的簡單方法嗎?
鏈接現在很好。 我同意Sarfraz的觀點,這是從PHP手冊頁的注釋中將XML與SImpleXML合並的不錯的解決方案,也可以與屬性一起使用:
function append_simplexml(&$simplexml_to, &$simplexml_from)
{
foreach ($simplexml_from->children() as $simplexml_child)
{
$simplexml_temp = $simplexml_to->addChild($simplexml_child->getName(), (string) $simplexml_child);
foreach ($simplexml_child->attributes() as $attr_key => $attr_value)
{
$simplexml_temp->addAttribute($attr_key, $attr_value);
}
append_simplexml($simplexml_temp, $simplexml_child);
}
}
也有用法示例。
使用SimpleXML是正確的方法,並且可能更容易。 這是有關如何使用它的很好的教程:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.