【问题标题】:How to create a xml file with specific structure using Php and Mysql? [duplicate]如何使用 Php 和 Mysql 创建具有特定结构的 xml 文件? [复制]
【发布时间】:2015-04-09 23:03:36
【问题描述】:
$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();
?>

我想使用上面的代码创建一个 XML 文件,但问题是它没有生成我真正需要的结构。

我需要一个具有以下结构的 XML 文件。如何生成它?

<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>

【问题讨论】:

  • 所需的xml结构为:

标签: php xml-parsing xml-formatting xml


【解决方案1】:

如果您想将users 作为根元素,则必须以这种方式创建 SimpleXMLElement。在循环中添加point 元素并设置属性。

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

$users = new SimpleXMLElement('<users/>');
foreach ($rows as $row) {
  $point = $users->addChild('point');
  $point['id'] = $row['id'];
}

echo $users->asXml();

输出:

<?xml version="1.0"?>
<users><point id="1"/><point id="2"/></users>

如果您想要/需要更多控制权,您将不得不切换到 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();

或者XMLWriter,它更适合大文件。

$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();

【讨论】:

  • 谢谢@ThW .....它对我有用!
猜你喜欢
  • 2015-03-23
  • 2014-06-24
  • 1970-01-01
  • 2012-11-25
  • 1970-01-01
  • 1970-01-01
  • 2017-05-14
  • 1970-01-01
  • 2011-04-12
相关资源
最近更新 更多