2017-03-02 38 views
0

有沒有簡單的方法將xml文件標籤轉換爲一行?我的XML文件($xml = simplexml_load_file('http://localhost/locations.xml');)包含:將xml標籤合併爲一個

<markers> 
    <marker> 
    <name>Chipotle Minneapolis</name> 
    <lat>44.947464</lat> 
    <lng>-93.320826</lng> 
    <category>Restaurant</category> 
    <address>3040 Excelsior Blvd</address> 
    <address2></address2> 
    <city>Minneapolis</city> 
    <state>MN</state> 
    <postal>55416</postal> 
    <country>US</country> 
    <phone>612-922-6662</phone> 
    <email>[email protected]</email> 
    <web>http://www.chipotle.com</web> 
    <hours1>Mon-Sun 11am-10pm</hours1> 
    <hours2></hours2> 
    <hours3></hours3> 
    <featured></featured> 
    </marker> 
</markers> 

轉換上面的代碼格式:

<markers><marker name="Chipotle Minneapolis" lat="44.947464" lng="-93.320826" category="Restaurant" address="3040 Excelsior Blvd" address2="" city="Minneapolis" state="MN" postal="55416" country="US" phone="612-922-6662" email="[email protected]" web="http://www.chipotle.com" hours1="Mon-Sun 11am-10pm" hours2="" hours3="" featured="" features="" /></markers> 

感謝

回答

1

簡單的工作SimpleXML

$string = '<markers>...</markers>'; 

$xml = new SimpleXMLElement($string); 

foreach ($xml->marker as $m) { 
    foreach ($m->children() as $c) { 
     $m->addAttribute($c->getName(), $c); 
     $trash[] = $c; 
    } 
    foreach ($trash as $t) unset($t[0]); 
} 

echo $xml->asXML(); 

即使您有多個元素,它也可以工作。當然,如果 只有一個,那麼不需要外部循環。請注意, 元素在單獨的迭代中被刪除(由unset()),不會混淆 的主要內容。

+0

關於'unset($ c [0])'和其他刪除元素的方法,請閱讀以下內容:[在SimpleXML for PHP中刪除具有特定屬性的子項](http://stackoverflow.com/questions/262351/remove-a-child-with-a-specific-attribute-in-simplexml-for-php/16062633#16062633) – sidyll

+1

此代碼有額外的空間。 – MahdiY

-1

把你的XML代碼在$string變量,並使用此代碼:

$xml = new SimpleXMLElement('<markers/>'); 

$marker = $xml->addChild('marker'); 

$string = "<markers> ... </markers>"; 

$string = simplexml_load_string($string); 

foreach($string->marker->children() as $name => $value) 
    $marker->addAttribute($value->getName(), $value); 

echo $xml->asXML(); 
+0

...甚至沒有接近正在請求的內容......它應該將''的子標籤移動到屬性中。 – CD001

+0

不僅這不能解決問題,但使用正則表達式來處理XML不是一個好主意! – sidyll

+0

代碼已更新!使用新的代碼並查看結果。 – MahdiY