我想在Codeigniter中使用PHP数组创建具有属性的XML数据(我正在使用Google Map,为此我必须创建xml数据,但必须以属性格式创建,并且要以xml标记格式获取数据,我正在从我使用MySqli从数据库创建的PHP数组whoich)
我已经尝试过了。
public function display_xml()
{
$this->load->dbutil();
$data = $this->db->query('select * from markers');
$config = array (
'root' => 'markers',
'element' => 'marker',
'newline' => "\n",
'tab' => "\t"
);
$xml = $this->dbutil->xml_from_result($data, $config);
$this->output->set_content_type('text/xml');
$this->output->set_output($xml);
}
我正在获得此输出。
<markers>
<marker>
<id>1</id>
<name>Love.Fish</name>
<address>580 Darling Street, Rozelle, NSW</address>
<lat>-33.861034</lat>
<lng>151.171936</lng>
<type>restaurant</type>
</marker>
<marker>
<id>2</id>
<name>Young Henrys</name>
<address>76 Wilford Street, Newtown, NSW</address>
<lat>-33.898113</lat>
<lng>151.174469</lng>
<type>bar</type>
</marker>
</markers>
我想要此输出
<markers>
<marker id="1" name="Billy Kwong" address="1/28 Macleay Street, Elizabeth Bay, NSW" lat="-33.869843" lng="-151.225769" type="restaurant"/>
<marker id="2" name="Love.Fish" address="580 Darling Street, Rozelle, NSW" lat="-33.861034" lng="151.171936" type="restaurant"/>
</markers>
答案 0 :(得分:0)
这里我们需要使用createAttribute。
public function display_xml()
{
$this->load->dbutil();
$data = $this->db->query('select * from markers');
$markers_data = $data->result_array();
$this->output->set_content_type('text/xml');
$dom = new DOMDocument("1.0");
// create root element
$root = $dom->createElement("markers");
$dom->appendChild($root);
foreach ($markers_data as $value)
{
// create child element
$marker = $dom->createElement("marker");
$root->appendChild($marker);
// create attribute node
$id = $dom->createAttribute("id");
$marker->appendChild($id);
// create attribute value node
$priceValue = $dom->createTextNode($value['id']);
$id->appendChild($priceValue);
// create attribute node
$name = $dom->createAttribute("name");
$marker->appendChild($name);
// create attribute value node
$nameValue = $dom->createTextNode($value['name']);
$name->appendChild($nameValue);
// create attribute node
$address = $dom->createAttribute("address");
$marker->appendChild($address);
// create attribute value node
$addressValue = $dom->createTextNode($value['address']);
$address->appendChild($addressValue);
// create attribute node
$lat = $dom->createAttribute("lat");
$marker->appendChild($lat);
// create attribute value node
$latValue = $dom->createTextNode($value['lat']);
$lat->appendChild($latValue);
// create attribute node
$lng = $dom->createAttribute("lng");
$marker->appendChild($lng);
// create attribute value node
$lngValue = $dom->createTextNode($value['lng']);
$lng->appendChild($lngValue);
// create attribute node
$type = $dom->createAttribute("type");
$marker->appendChild($type);
// create attribute value node
$typeValue = $dom->createTextNode($value['type']);
$type->appendChild($typeValue);
}
// save and display tree
echo $dom->saveXML();
}