0
$sql = "SELECT * FROM users ORDER BY 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 the XML file
    $fp = fopen("users100r.xml","wb");
//Write the XML nodes
    fwrite($fp,$xml->asXML());
    fclose($fp);
    echo $xml->saveXML();
?>

I want to create an XML file using the above code, but the problem is that it did not generate a required structure, which I actually needed.

I need an XML file with following structure. How can I 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>
1
  • Required xml structure is as: <users> <point id="1" lat="24.24707031" lng="68.16540527" address="Pakistan"/> <point id="2" lat="34.24707031" lng="63.16540527" address="Lahore"/> </users> Commented Apr 9, 2015 at 23:05

1 Answer 1

1

If you want users as the root element, you will have to create the SimpleXMLElement that way. In the loop add the point element and set the attributes.

$rows = [
  ['id' => 1],
  ['id' => 2]
];

$users = new SimpleXMLElement('<users/>');
foreach ($rows as $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 you want/need more control you will have to switch to DOM.

$dom = new DOMDocument();
$users = $dom->appendChild($dom->createElement('users'));
foreach ($rows as $row) {
  $point = $users->appendChild($dom->createElement('point'));
  $point->setAttribute('id', $row['id']);
}

echo $dom->saveXml();

Or to XMLWriter, which is better for large files.

$xml = new XMLWriter();
$xml->openURI('php://output');
$xml->startDocument();
$xml->startElement('users');
foreach ($rows as $row) {
  $xml->startElement('point');
  $xml->writeAttribute('id', $row['id']);
  $xml->endElement();
}
$xml->endElement();
$xml->endDocument();
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.