在PHP中是否有类似json_encode()的xml_encode()?

lul*_*ala 19 php xml ajax

在PHP中,使用json_encode().很容易传回json对象.
但是有没有相当于XML的XML?

Sep*_*eph 8

您可以定义自己的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));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 工作正常,请注意,它太聪明了,如果你有一个以's'结尾的标签名称 - 它将自动制作一个单一形式的标签并将其添加到内... ...使kml具有'coordinates'-tag,不应该有任何'坐标'子标签):-P (3认同)

phi*_*hag 7

JSON本身可以表达php数组,整数,字符串等.XML没有这样的概念 - 只是元素,属性和文本.如果要逐字传输对象,请使用JSON.如果要实现复杂的API,请使用XML,例如php DOM接口.


ant*_*njs 5

您可以使用xmlrpc_encode

 xmlrpc_encode ($your_array);
Run Code Online (Sandbox Code Playgroud)

请小心,因为此功能是实验性的。

参考:http//php.net/manual/en/function.xmlrpc-encode.php