Laravel 8 实现 PHP 的 DOM XML 函数输出 XML

Laravel 8 implement PHP's DOM XML functions to output XML

我是Laravel PHP框架的新手,所以不是很熟悉。 我需要一些帮助来实现 Google Maps. To retrieve the latitude longitude. And also, some info from a database that I created locally in PHPMyAdmin for markers. The problem I have is that Laravel doesn't recognize MySQL functions (undefined functions). I saw in documentation that it uses facades DB::raw(your SQL), but I tried to implement it without a result. I don't upload any code because I just created the skeleton and take the code from Google Maps API 中的示例代码。我发现 MySQLi 替换了 MySQL 函数,所以我修改了代码,但我仍然没有弄清楚 domxml_new_doc("1.0").

$host = "127.0.0.1";
$username = "user";
$password = "";
$database = "db";
$con = mysqli_connect($host, $username, $password, $database);

// Start XML file, create parent node
$doc = domxml_new_doc("1.0"); //Undefined function
$node = $doc->create_element("markers");
$parnode = $doc->append_child($node);

// Opens a connection to a MySQL server
$connection = mysqli_connect('localhost', $username, $password);
if (!$connection) {
    die('Not connected : ' . mysqli_error($con));
}

// Set the active MySQL database
$db_selected = mysqli_select_db($database, $connection);
if (!$db_selected) {
    die ('Can\'t use db : ' . mysqli_error($con));
}

// Select all the rows in the markers table
$query = "SELECT * FROM gasstations WHERE 1";
$result = mysqli_query($con, $query);
if (!$result) {
    die('Invalid query: ' . mysqli_error($con));
}

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

// Iterate through the rows, adding XML nodes for each
while ($row = @mysqli_fetch_assoc($result)) {
    // Add to XML document node
    $node = $doc->create_element("marker");
    $newnode = $parnode->append_child($node);

    $newnode->set_attribute("id", $row['id']);
    $newnode->set_attribute("name", $row['name']);
    $newnode->set_attribute("address", $row['address']);
    $newnode->set_attribute("lat", $row['lat']);
    $newnode->set_attribute("lng", $row['lng']);
    $newnode->set_attribute("type", $row['type']);
}

$xmlfile = $doc->dump_mem();
echo $xmlfile;

domxml_new_doc() 是旧的 PHP 4 函数,当前 PHP 中不存在。使用 DOMDocument class 及其方法。

这是一个例子:

$records = [
    ['id' => 'id42', 'name' => 'foo']
];

$document = new DOMDocument('1.0', 'UTF-8');
$document->appendChild(
    $markers = $document->createElement('markers')
);
foreach ($records as $row) {
    $markers->appendChild(
        $marker = $document->createElement('marker')
    );
    $marker->setAttribute('id', $row['id']);
    $marker->setAttribute('name', $row['name']);
}

$document->formatOutput = TRUE;
echo $document->saveXML();

输出:

<?xml version="1.0" encoding="UTF-8"?>
<markers>
  <marker id="id42" name="foo"/>
</markers>