I have this Textfile (namelist.txt):
{"0":"Mr Tony Test","1":"Ms Tina Testy"}
And I try to convert it into XML:
<?php
$xml = new DOMDocument();
$names = json_decode(file_get_contents('namelist.txt'));
foreach ($names as $name)
{
$xml_name = $xml->createElement($name);
}
$xml->save("rss.xml");
?>
I get the following Error:
Fatal error: Uncaught exception 'DOMException' with message 'Invalid Character Error' in C:\xampp\htdocs\xibo\rss.php:6 Stack trace: #0 C:\xampp\htdocs\xibo\rss.php(6): DOMDocument->createElement('Mr Tony Te...') #1 {main} thrown in C:\xampp\htdocs\xibo\rss.php on line 6
Is is even possible like this?
Edit 1:
Tried a solution by @spiky but I get a blank page as result:
<?php
$obj=('namelist.txt');
function json_to_xml($obj){
$str = "";
if(is_null($obj))
return "<null/>";
elseif(is_array($obj)) {
//a list is a hash with 'simple' incremental keys
$is_list = array_keys($obj) == array_keys(array_values($obj));
if(!$is_list) {
$str.= "<hash>";
foreach($obj as $k=>$v)
$str.="<item key=\"$k\">".json_to_xml($v)."</item>".CRLF;
$str .= "</hash>";
} else {
$str.= "<list>";
foreach($obj as $v)
$str.="<item>".json_to_xml($v)."</item>".CRLF;
$str .= "</list>";
}
return $str;
} elseif(is_string($obj)) {
return htmlspecialchars($obj) != $obj ? "<![CDATA[$obj]]>" : $obj;
} elseif(is_scalar($obj))
return $obj;
else
throw new Exception("Unsupported type $obj");
}
?>