How can I group this output?


#1

I’m writing a script that creates an XML document for a desk phone to load.

It’s working but not quite how I want.

I only want to output a Menu block if the Category Group changes, But I’m not sure how to test for that in my code.

Here is the output I have currently:
[php]
?xml version=“1.0” encoding=“UTF-8”?>

Yealink [/php]

Here is the output I want:
[php]?xml version=“1.0” encoding=“UTF-8”?>

Yealink [/php]

Here is my script:
[php]<?php

header(“Content-type: text/xml”);

$host = “localhost”;
$user = “web”;
$pass = “28t46wgjhrksf98yhkj”;
$database = “test”;

$linkID = mysql_connect($host, $user, $pass) or die(“Could not connect to host.”);
mysql_select_db($database, $linkID) or die(“Could not find database.”);

$query = “SELECT CategoryGroup,ContactName,Phone1,Phone2,Phone3 FROM phonebook ORDER BY CategoryGroup”;
$resultID = mysql_query($query, $linkID) or die(“Data not found.”);

$xml_output = “<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n”;
$xml_output .= “\n”;
$xml_output .= “Yealink\n”;

for($x = 0 ; $x < mysql_num_rows($resultID) ; $x++){
$row = mysql_fetch_assoc($resultID);
$xml_output .= “\t<Menu Name=”" . $row[‘CategoryGroup’] . “”>\n";
$xml_output .= “\t\t<Unit Name=”" . $row[‘ContactName’] . “” default_photo=“Resource:” " . “Phone3=”" . $row[‘Phone3’] . “” " . “Phone2=”" . $row[‘Phone2’] ."" " . “Phone1=”" . $row[‘Phone1’] . “”/>\n";
$xml_output .= “\t\n”;
}

$xml_output .= “”;

echo $xml_output;

?>
[/php]


#2

Two things.

First, don’t use mysql_ functions. PDO is best, mysqli is the minimum.
Second, you don’t need to create the xml strings yourself, http://php.net/manual/en/example.xmlwriter-simple.php is one tool to do it for you.

You just need an if block to test what you are checking for.


#3

I’m working in a very old environment with PHP 5.1.6, I will have to see if I have those functions.


#4

It doesn’t look like xmlwriter will work for me because my device wants spaces in the Element names which isn’t valid.

‘’ and ‘’ both contain spaces.


#5

Ahh, yeah, spaces in the XML tag is not compliant XML.

I would say something like this, needs testing of course.
[php]
$category = null;
for($x = 0 ; $x < mysql_num_rows($resultID) ; $x++){
$row = mysql_fetch_assoc($resultID);
$xml_output .= “\t<Menu Name=”" . $row[‘CategoryGroup’] . “”>\n";

while(true) {
 	if($category != $row['CategoryGroup'])
 		break;
	$xml_output .= "\t\t<Unit Name=\"" . $row['ContactName'] . "\" default_photo=\"Resource:\" " . "Phone3=\"" . $row['Phone3'] . "\" " . "Phone2=\"" . $row['Phone2'] ."\" " . "Phone1=\"" .  $row['Phone1'] . "\"/>\n";
	$category = $row['CategoryGroup'];
 }
 
 $xml_output .= "\t</Menu>\n";

}

$xml_output .= “”;

echo $xml_output;[/php]