我有这个文本文件(namelist.txt):
{“0”:“Tony Test先生”,“1”:“Tina Testy女士”}
我尝试将其转换为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");
?>
我收到以下错误:
致命错误:未捕获的异常'DOMException',消息'无效 C:\ xampp \ htdocs \ xibo \ rss.php中的字符错误:6堆栈跟踪:#0 C:\ xampp \ htdocs \ xibo \ rss.php(6):DOMDocument-&gt; createElement('Mr Tony 在第6行的C:\ xampp \ htdocs \ xibo \ rss.php中抛出#... {main}
甚至可能是这样吗?
修改1:
尝试了@spiky的解决方案,但结果是一个空白页:
<?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");
}
?>
答案 0 :(得分:1)
如果您解码JSON,则该对象具有两个属性(0
和1
)。
var_dump(json_decode('{"0":"Mr Tony Test","1":"Ms Tina Testy"}'));
输出:
object(stdClass)#1 (2) {
["0"]=>
string(12) "Mr Tony Test"
["1"]=>
string(13) "Ms Tina Testy"
}
迭代属性并将值用作元素名称。但它们不是有效的名字。以下是产生错误的静态示例:
$document = new DOMDocument();
$document->createElement('name with spaces');
输出:
Fatal error: Uncaught exception 'DOMException' with message
'Invalid Character Error' in /tmp/...
因此,您要确保生成有效的XML。喜欢这个:
$json = json_decode('{"0":"Mr Tony Test","1":"Ms Tina Testy"}');
$document = new DOMDocument();
$names = $document->appendChild(
$document->createElement('names')
);
foreach ($json as $value) {
$names
->appendChild($document->createElement('name'))
->appendChild($document->createTextNode($value));
}
$document->formatOutput = TRUE;
echo $document->saveXml();
输出:
<?xml version="1.0"?>
<names>
<name>Mr Tony Test</name>
<name>Ms Tina Testy</name>
</names>
最好为XML使用可定义的节点结构,而不是由数据定义的结构。
您将结果命名为xml文件&#39; rss.xml&#39;。 RSS是一种定义的格式。因此,如果您想生成RSS,则必须生成特定节点。
$json = json_decode('{"0":"Mr Tony Test","1":"Ms Tina Testy"}');
$document = new DOMDocument();
$rss = $document->appendChild($document->createElement('rss'));
$rss->setAttribute('version', '2.0');
$channel = $rss->appendChild($document->createElement('channel'));
foreach ($json as $value) {
$item = $channel->appendChild($document->createElement('item'));
$item
->appendChild($document->createElement('title'))
->appendChild($document->createTextNode($value));
}
$document->formatOutput = TRUE;
echo $document->saveXml();
输出:
<?xml version="1.0"?>
<rss version="2.0">
<channel>
<item>
<title>Mr Tony Test</title>
</item>
<item>
<title>Ms Tina Testy</title>
</item>
</channel>
</rss>