【问题标题】:Laravel 8 implement PHP's DOM XML functions to output XMLLaravel 8 实现 PHP 的 DOM XML 函数输出 XML
【发布时间】:2021-03-24 13:37:51
【问题描述】:

我是 Laravel PHP 框架的新手,所以对它不是很熟悉。 我需要一些帮助来实现来自Google Maps 的示例代码。检索纬度经度。此外,我在 PHPMyAdmin 中为标记本地创建的数据库中的一些信息。我遇到的问题是 Laravel 无法识别 MySQL 函数(未定义函数)。我在文档中看到它使用门面DB::raw(your SQL),但我试图实现它但没有结果。我没有上传任何代码,因为我刚刚创建了骨架并从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;

【问题讨论】:

    标签: php mysql xml google-maps-markers laravel-8


    【解决方案1】:

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

    这是一个例子:

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

    【讨论】:

      猜你喜欢
      • 2015-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多