Przedstawiam krótką procedurkę, która konwertuje wejściowy obiekt do XML'a.
/**
* _to_xml
*
* @author Michal Luberda
* @version 0.0.5
* @access public
* @param mixed $v init object / array to convert
* @return string converted XML
*/
function _to_xml ($v, $s_el = "", $i = 0)
{
$i++;
$s = "";
if (is_array ($v)) {
foreach ($v as $s_k => $v2) {
if (! is_numeric ($s_k))
$s .= "<" . $s_k . ">";
elseif ($s_el)
$s .= "<" . $s_el . ">";
$s .= _to_xml ($v2, "", $i);
if (! is_numeric ($s_k))
$s .= "";
elseif ($s_el)
$s .= "";
}
}
elseif (is_object ($v)) {
foreach ($v as $s_k => $v2) {
if (! is_array ($v2))
$s .= "<" . $s_k . ">";
elseif (! $s_el && $s_k)
$s .= "<" . $s_k . ">";
$s .= _to_xml ($v2, $s_k, $i);
if (! is_array ($v2))
$s .= "";
elseif (! $s_el && $s_k)
$s .= "";
}
}
elseif ($v) {
$s .= $v;
}
return $s;
}
Funkcja nie generuje żadnych atrybutów, a tablice konwertowane są w ten sposób, że, jeśli jej elementy nie są skojarzone z żadnym kluczem tekstowym, to używana jest właściwość obiektu do której jest przypisana jako nazwa elementu, na przykład:
$o = new stdClass ();
$o -> id = 1;
$o -> title = "Title";
$o -> content = "Content";
$a = array ();
$o_attachment = new stdClass ();
$o_attachment -> id = 1;
$o_attachment -> file = "file.jpg";
$a[] = $o_attachment;
$o_attachment = new stdClass ();
$o_attachment -> id = 2;
$o_attachment -> file = "test.png";
$a[] = $o_attachment;
$o -> attachments -> attachment = $a;
print _to_xml ($o);
wygeneruje taki oto XML
<id>1</id>
<title>Title</title>
<content>Content</content>
<attachments>
<attachment>
<id>1</id>
<file>file.jpg</file>
</attachment>
<attachment>
<id>2</id>
<file>test.png</file>
</attachment>
</attachments>Michał Luberda - Wenecja marzec 2010