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

Tags: , , , ,



I am new to the Laravel PHP framework, so I am not so familiar with it. I need some help implementing the sample code from 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. I found that MySQLi replaced MySQL functions, so I modified the code, but I still not figured out the 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;

Answer

domxml_new_doc() is an old PHP 4 function and does not exists in current PHP. Use the DOMDocument class and its methods.

Here is an example:

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

Output:

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


Source: stackoverflow