我使用以下代码从sql数据库生成XML文档,目前工作正常。
<?php
include ("config/init.php");
$query = "SELECT * FROM locations";
$result = mysqli_query($mysqli_conn, $query) or die ("Error in query: $query. ".mysql_error());
//Top of xml file
$_xml .="<markers>";
while($row = mysqli_fetch_array($result)) {
$_xml .="<marker>";
$_xml .="<id>".$row['id']."</id>";
$_xml .="<name>".$row['name']."</name>";
$_xml .="<address>".$row['address']."</address>";
$_xml .="<lat>".$row['lat']."</lat>";
$_xml .="<lng>".$row['lng']."</lng>";
$_xml .="</marker>";
}
$_xml .="</markers>";
//Parse and create an xml object using the string
$xmlobj=new SimpleXMLElement($_xml);
//write to an XML file
$xmlobj->asXML('locations.xml');
?>
这将创建一个名为“locations.xml”的XML文档,如下所示:
<markers>
<marker>
<id>1</id>
<name>NAME</name>
<address>ADDRESS</address>
<lat>23.234567</lat>
<lng>-1.987654</lng>
</marker>
</markers>
但是我需要它采用这样的格式:
<markers>
<marker name="NAME" lat="23.234567" lng="-1.987654" address="ADDRESS" />
</markers>
最好的是什么?我做这种事情比较新,所以任何指导都会很棒。
答案 0 :(得分:1)
Php有几个XML Manipulation对象。根据我的经验,DOM最适合写作,而SimpleXML最适合阅读。
<?php
$xmlObj = new DOMDocument('1.0', 'utf-8');
$xmlObj->formatOutput = true;
$root = $xmlObj->createElement('markers') ;
$root = $xmlObj->appendChild( $root );
$row = array('id'=>5677,'name'=>'Name','address'=>'404 Not Found Rd Ste ', 'lat'=>'10.', 'lng'=>'50.');
for ( $i = 1; $i < 10; $i++ )
{
$currentRow = $xmlObj->createElement('marker');
foreach ( $row as $key => $value )
{ $currentRow->setAttribute($key,$value.$i); }
$root->appendChild( $currentRow );
}
print $xmlObj->saveXML();
?>