xml parsing - How to create a xml file with specific structure using Php and Mysql? -
this question has answer here:
$sql = "select * users order rand() limit 100"; $xml = new simplexmlelement('<xml/>'); $result = $conn->query($sql); if ($result->num_rows > 0) { while ($row = $result->fetch_array()) { $users = $xml->addchild('users'); $users->addchild('id',$row['sno']); $users->addchild('lat',$row['lat']); $users->addchild('long',$row['lng']); $users->addchild('address',$row['address']); } $conn->close(); //create xml file $fp = fopen("users100r.xml","wb"); //write xml nodes fwrite($fp,$xml->asxml()); fclose($fp); echo $xml->savexml(); ?>
i want create xml file using above code, problem did not generate required structure, needed.
i need xml file following structure. how can generate it?
<users> <point id="1" lat="24.24707031" lng="68.16540527" address="pakistan"/> <point id="2" lat="34.24707031" lng="63.16540527" address="lahore"/> <point id="3" lat="28.24707031" lng="55.16540527" address="karachi"/> </users>
if want users
root element, have create simplexmlelement way. in loop add point
element , set attributes.
$rows = [ ['id' => 1], ['id' => 2] ]; $users = new simplexmlelement('<users/>'); foreach ($rows $row) { $point = $users->addchild('point'); $point['id'] = $row['id']; } echo $users->asxml();
output:
<?xml version="1.0"?> <users><point id="1"/><point id="2"/></users>
if want/need more control have switch dom.
$dom = new domdocument(); $users = $dom->appendchild($dom->createelement('users')); foreach ($rows $row) { $point = $users->appendchild($dom->createelement('point')); $point->setattribute('id', $row['id']); } echo $dom->savexml();
or xmlwriter, better large files.
$xml = new xmlwriter(); $xml->openuri('php://output'); $xml->startdocument(); $xml->startelement('users'); foreach ($rows $row) { $xml->startelement('point'); $xml->writeattribute('id', $row['id']); $xml->endelement(); } $xml->endelement(); $xml->enddocument();