Search code examples
phpsqlxmlexportexport-to-xml

Exporting to XML with PHP


Trying the following PHP export to XML in order to create a remote phonebook for a Yealink SIP-T46G. Managed to get so far but currently exporting a an XML format that isn't valid to use on the phones. Looking throughout this site, I have found similar questions but have not managed to get this working.

<?php
include './data/datalogin.php';
$sql = mysqli_query($con,"SELECT contact_id, name, phone, cell FROM contact ORDER BY name ASC");
$xml = "<root_contact>";

while($r = mysqli_fetch_array($sql))
{
$xml .= "<contact>";
$xml .= $display_name=$r["name"];
$xml .= $office_number=$r["phone"];
$xml .= $mobile_number=$r["cell"];
$xml .= "</contact>";
}
$xml .= "</root_contact>";

$sxe = new SimpleXMLElement($xml);
$dom = new DOMDocument('1,0');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($sxe->asXML());
echo $dom->saveXML();
$dom->save('phonebookt47.xml');
?>

Output currently is in the format, which is just adding the phone number immediately after the display instead of as the desired format further below.

<contact>SampleCompany01666666666</contact>

Need it to to export in the below format

<contact display_name="SampleCompanyName" office_number="01666666666" mobile_number="07945444444"/>

I don't think it is far away but any help is appreciated.


Solution

  • You need to put the attributes in the content tags like so:

    <?php
    include './data/datalogin.php';
    $sql = mysqli_query($con,"SELECT contact_id, name, phone, cell FROM contact ORDER BY name ASC");
    
    $xml = "<root_contact>";
    
    while($r = mysqli_fetch_array($sql))
    {
       $xml .= '<contact display_name="'.$r["name"].'" office_number="'.$r["phone"].'" mobile_number="'.$r["cell"].'" />';
    }
    
    $xml .= "</root_contact>";
    
    $sxe = new SimpleXMLElement($xml);
    $dom = new DOMDocument('1,0');
    $dom->preserveWhiteSpace = false;
    $dom->formatOutput = true;
    $dom->loadXML($sxe->asXML());
    
    echo $dom->saveXML();
    
    $dom->save('phonebookt47.xml');
    ?>