将数据转换为XML

时间:2018-02-07 19:58:13

标签: php xml

我想根据从数据库获取的位置在谷歌地图上显示数据,但我需要将我的数据转换为XML。

我遇到了这种转换的问题。

<?php

    function parseToXML($htmlStr)
    {
        $xmlStr=str_replace('<','&lt;',$htmlStr);
        $xmlStr=str_replace('>','&gt;',$xmlStr);
        $xmlStr=str_replace('"','&quot;',$xmlStr);
        $xmlStr=str_replace("'",'&#39;',$xmlStr);
        $xmlStr=str_replace("&",'&amp;',$xmlStr);
        return $xmlStr;
    }

    // Opens a connection to a MySQL server
    $dsn = 'mysql:host=localhost;dbname=map';
    $pdo = new PDO($dsn, 'root', '');

    // Select all the rows in the markers table
    $query = $pdo->prepare('SELECT * FROM markers WHERE 1');
    $query->execute();
    $result = $query->fetchAll(PDO::FETCH_ASSOC);

    header("Content-type: text/xml");

    // Start XML file, echo parent node
    echo '<markers>';

    // Iterate through the rows, printing XML nodes for each
    foreach ($result as $key => $row) {
      // Add to XML document node
      echo '<marker ';
      echo 'id="' . $ind . '" ';
      echo 'name="' . parseToXML($row['name']) . '" ';
      echo 'address="' . parseToXML($row['address']) . '" ';
      echo 'lat="' . $row['lat'] . '" ';
      echo 'lng="' . $row['lng'] . '" ';
      echo 'type="' . $row['type'] . '" ';
      echo '/>';
    }

    // End XML file
    echo '</markers>';

?>

我一直收到此错误

此页面包含以下错误:

error on line 1 at column 18: error parsing attribute name
Below is a rendering of the page up to the first error.

1 个答案:

答案 0 :(得分:0)

不要通过使用字符串连接构建树来将XML视为文本文件。考虑使用一个DOM库,其中PHP有各种类,如DOMDocument和SimpleXML。并使用htmlspecialchars将特殊字符转换为HTML实体。

// Opens a connection to a MySQL server
...

// Select all the rows in the markers table
...

header("Content-type: text/xml");

// INITIALIZE DOM DOCUMENT
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->formatOutput = true;
$dom->preserveWhiteSpace = false;

// CREATE ROOT
$root = $dom->createElement("markers");
$dom->appendChild($root);

foreach ($result as $key => $row) {
   // CREATE NEW MARKER ELEMENT
   $markerNode = $dom->createElement('marker');
   $root->appendChild($markerNode);

   // ADD ATTRIBUTES TO MARKER
   $markerNode->setAttribute("id", $ind);
   $markerNode->setAttribute("name", htmlspecialchars($row['name']));
   $markerNode->setAttribute("address", htmlspecialchars($row['address']));
   $markerNode->setAttribute("lat", $row['lat']);
   $markerNode->setAttribute("lng", $row['lng']);
   $markerNode->setAttribute("type", $row['type']);
}

// OUTPUT RESULT TREE
echo $dom->saveXML();