Your problem is that you set multiple values to the same node. So you are always overwriting the attribute values with the latest lat/long value.
Instead you need to add a new element per each lat/long pair because XML elements do not have duplicate attributes.
Some example code based on your question, as you can see I introduce some functions to keep things more modular:
$result = $db->query("SELECT * FROM usersline");
if (!$result || !count($result)) {
echo "<p>Ëèíèé íå îáíàðóæåíî!</p>";
return;
}
$doc = new DOMDocument("1.0");
$doc->loadXML('<marker/>');
$marker = $doc->documentElement;
foreach ($result as $mar) {
$line = $doc->createElement('line');
$attributes = array_map_array(['id_line', 'colour' => 'color', 'width'], $mar);
element_add_attributes($line, $attributes);
foreach (coordinates_to_array($mar['coordinats']) as $latlong) {
$point = $doc->createElement('point');
element_add_attributes($point, $latlong);
$line->appendChild($point);
}
$marker->appendChild($line);
}
header("Content-type: text/xml");
echo $doc->saveXML();
function element_add_attributes(DOMElement $element, array $attributes)
{
foreach ($attributes as $name => $value) {
if (!is_string($name)) continue;
$element->setAttribute($name, $value);
}
}
function array_map_array(array $map, array $array)
{
$result = array();
foreach ($map as $alias => $name) {
$source = is_string($alias) ? $alias : $name;
$result[$name] = $array[$source];
}
return $result;
}
function coordinates_to_array($coordinates)
{
$result = array();
$coordinatePairs = explode(";", $coordinates);
foreach ($coordinatePairs as $coordinatePair) {
list($pair['lat'], $pair['lng']) = explode(',', $coordinatePair, 2) + ['', ''];
$result[] = $pair;
}
return $result;
}
I hope this example is helpful and shows you some ways how you can put a problem apart so that your code becomes more easy and more stable.
To make use of $db->query(...)
first define a class that has the query
method:
class DB {
public function query($sql) {
$dbhandle = mysql_query($sql);
$result = array();
while ($mar = mysql_fetch_array($dbhandle))
$result[] = $mar
;
return $result;
}
}
Then instantiate it:
$db = new DB();
You can then use the code above for that part.
For the problem with the PHP 5.4 array notation for example in this line:
$attributes = array_map_array(['id_line', 'colour' => 'color', 'width'], $mar);
First of all extract the array out of it:
$mapping = ['id_line', 'colour' => 'color', 'width'];
$attributes = array_map_array($mapping, $mar);
Then define the array with the array(
and )
notation instead of [
and ]
:
$mapping = array('id_line', 'colour' => 'color', 'width');
$attributes = array_map_array($mapping, $mar);
Do so as well in other places, e.g.
['', '']
becomes
array('', '')
and similar.