2017-03-02 85 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