将xml标签合并为一个

时间:2017-03-02 16:49:15

标签: php xml

有没有简单的方法将xml文件标记转换为一行?我的xml文件($xml = simplexml_load_file('http://localhost/locations.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>info@chipotle.com</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="info@chipotle.com" web="http://www.chipotle.com" hours1="Mon-Sun 11am-10pm" hours2="" hours3="" featured="" features="" /></markers>

由于

2 个答案:

答案 0 :(得分: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();

即使您有多个marker元素,它也会有效。当然,如果 你只有一个,那么不需要外循环。请注意 元素在单独的迭代中被移除(通过unset())而不是混乱 主要的一个。

答案 1 :(得分:-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();
相关问题