在PHP中,使用json_encode()
可以很容易地传回json对象。
但是,有没有与此等效的XML?
发布于 2011-09-30 18:34:08
JSON可以原生表达php数组、整数、字符串等。XML没有这样的概念--只有元素、属性和文本。如果您想逐字传输对象,请使用JSON。如果你想实现一个复杂的API,可以使用XML,例如php DOM interface。
发布于 2013-08-19 14:59:54
您可以定义自己的xml_encode()
函数,例如http://darklaunch.com/2009/05/23/php-xml-encode-using-domdocument-convert-array-to-xml-json-encode中的函数
function xml_encode($mixed, $domElement=null, $DOMDocument=null) {
if (is_null($DOMDocument)) {
$DOMDocument =new DOMDocument;
$DOMDocument->formatOutput = true;
xml_encode($mixed, $DOMDocument, $DOMDocument);
echo $DOMDocument->saveXML();
}
else {
// To cope with embedded objects
if (is_object($mixed)) {
$mixed = get_object_vars($mixed);
}
if (is_array($mixed)) {
foreach ($mixed as $index => $mixedElement) {
if (is_int($index)) {
if ($index === 0) {
$node = $domElement;
}
else {
$node = $DOMDocument->createElement($domElement->tagName);
$domElement->parentNode->appendChild($node);
}
}
else {
$plural = $DOMDocument->createElement($index);
$domElement->appendChild($plural);
$node = $plural;
if (!(rtrim($index, 's') === $index)) {
$singular = $DOMDocument->createElement(rtrim($index, 's'));
$plural->appendChild($singular);
$node = $singular;
}
}
xml_encode($mixedElement, $node, $DOMDocument);
}
}
else {
$mixed = is_bool($mixed) ? ($mixed ? 'true' : 'false') : $mixed;
$domElement->appendChild($DOMDocument->createTextNode($mixed));
}
}
}
发布于 2016-03-05 00:44:32
您可以使用xmlrpc_encode
。
xmlrpc_encode ($your_array);
要小心,因为这个函数是实验性的。
https://stackoverflow.com/questions/7609095
复制相似问题