首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在PHP中有没有像json_encode()这样的xml_encode()?

在PHP中有没有像json_encode()这样的xml_encode()?
EN

Stack Overflow用户
提问于 2011-09-30 18:28:56
回答 6查看 37.8K关注 0票数 21

在PHP中,使用json_encode()可以很容易地传回json对象。

但是,有没有与此等效的XML?

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2011-09-30 18:34:08

JSON可以原生表达php数组、整数、字符串等。XML没有这样的概念--只有元素、属性和文本。如果您想逐字传输对象,请使用JSON。如果你想实现一个复杂的API,可以使用XML,例如php DOM interface

票数 7
EN

Stack Overflow用户

发布于 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中的函数

代码语言:javascript
复制
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));
        }
    }
}
票数 10
EN

Stack Overflow用户

发布于 2016-03-05 00:44:32

您可以使用xmlrpc_encode

代码语言:javascript
复制
 xmlrpc_encode ($your_array);

要小心,因为这个函数是实验性的。

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

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7609095

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档