我想知道在PHP(或一些广泛使用的PHP库)中是否存在能够将关联数组转换为XML文档的函数。
我搜索了很多,只能找到不输出有效XML的函数。我相信我正在测试它们的数组是正确构造的,因为它可以正确地用于使用json_encode生成JSON文档。但是,它相当大,它嵌套在四个层次上,这可以解释为什么我到目前为止尝试过的函数都失败了。
最终,我会编写代码来自己生成XML,但肯定必须有更快的方法来实现这一点。
答案 0 :(得分:7)
我意识到我在这里是Johnny-Come-Lately,但我正在处理非常相同的问题 - 我在那里发现的教程将几乎(但不完全在单元测试中)覆盖它。
经过多次挫折和研究之后,这就是我提出的问题
json_decode( json_encode( simplexml_load_string( $string ) ), TRUE );
备注:
来自http://www.devexp.eu/2009/04/11/php-domdocument-convert-array-to-xml/
/// Converts an array to XML
/// - http://www.devexp.eu/2009/04/11/php-domdocument-convert-array-to-xml/
/// @param <array> $array The associative array you want to convert; nested numeric indices are OK!
function getXml( array $array ) {
$array2XmlConverter = new XmlDomConstructor('1.0', 'utf-8');
$array2XmlConverter->xmlStandalone = TRUE;
$array2XmlConverter->formatOutput = TRUE;
try {
$array2XmlConverter->fromMixed( $array );
$array2XmlConverter->normalizeDocument ();
$xml = $array2XmlConverter->saveXML();
// echo "\n\n-----vvv start returned xml vvv-----\n";
// print_r( $xml );
// echo "\n------^^^ end returned xml ^^^----\n"
return $xml;
}
catch( Exception $ex ) {
// echo "\n\n-----vvv Rut-roh Raggy! vvv-----\n";
// print_r( $ex->getCode() ); echo "\n";
// print_r( $->getMessage() );
// var_dump( $ex );
// echo "\n------^^^ end Rut-roh Raggy! ^^^----\n"
return $ex;
}
}
...这里是用于$array2XmlConverter
对象的类:
/**
* Extends the DOMDocument to implement personal (utility) methods.
* - From: http://www.devexp.eu/2009/04/11/php-domdocument-convert-array-to-xml/
* - `parent::` See http://www.php.net/manual/en/class.domdocument.php
*
* @throws DOMException http://www.php.net/manual/en/class.domexception.php
*
* @author Toni Van de Voorde
*/
class XmlDomConstructor extends DOMDocument {
/**
* Constructs elements and texts from an array or string.
* The array can contain an element's name in the index part
* and an element's text in the value part.
*
* It can also creates an xml with the same element tagName on the same
* level.
*
* ex:
\verbatim
<nodes>
<node>text</node>
<node>
<field>hello</field>
<field>world</field>
</node>
</nodes>
\verbatim
*
*
* Array should then look like:
\verbatim
array(
"nodes" => array(
"node" => array(
0 => "text",
1 => array(
"field" => array (
0 => "hello",
1 => "world",
),
),
),
),
);
\endverbatim
*
* @param mixed $mixed An array or string.
*
* @param DOMElement[optional] $domElement Then element
* from where the array will be construct to.
*
*/
public function fromMixed($mixed, DOMElement $domElement = null) {
$domElement = is_null($domElement) ? $this : $domElement;
if (is_array($mixed)) {
foreach( $mixed as $index => $mixedElement ) {
if ( is_int($index) ) {
if ( $index == 0 ) {
$node = $domElement;
}
else {
$node = $this->createElement($domElement->tagName);
$domElement->parentNode->appendChild($node);
}
}
else {
$node = $this->createElement($index);
$domElement->appendChild($node);
}
$this->fromMixed($mixedElement, $node);
}
}
else {
$domElement->appendChild($this->createTextNode($mixed));
}
}
} // end of class
答案 1 :(得分:5)
没有。至少没有这样的内置功能。写它根本不是一个问题。
肯定必须有更快的方法来做到这一点
如何在数组中表示属性?我可以假设键是标签,值是这个标签的内容。
基本PHP数组 - &gt; JSON工作得很好,因为那些结构......好吧......几乎一样。
答案 2 :(得分:1)
PHP的DOMDocument
对象可能就是你要找的东西。以下是使用此类将多维数组转换为xml文件的示例链接 - http://www.php.net/manual/en/book.dom.php#78941
答案 3 :(得分:1)
拨打强>
// $data = array(...);
$dataTransformator = new DataTransformator();
$domDocument = $dataTransformator->data2domDocument($data);
$xml = $domDocument->saveXML();
<强> DataTransformator 强>
class DataTransformator {
/**
* Converts the $data to a \DOMDocument.
* @param array $data
* @param string $rootElementName
* @param string $defaultElementName
* @see MyNamespace\Dom\DataTransformator#data2domNode(...)
* @return Ambigous <DOMDocument>
*/
public function data2domDocument(array $data, $rootElementName = 'data', $defaultElementName = 'item') {
return $this->data2domNode($data, $rootElementName, null, $defaultElementName);
}
/**
* Converts the $data to a \DOMNode.
* If the $elementContent is a string,
* a DOMNode with a nested shallow DOMElement
* will be (created if the argument $node is null and) returned.
* If the $elementContent is an array,
* the function will applied on every its element recursively and
* a DOMNode with a nested DOMElements
* will be (created if the argument $node is null and) returned.
* The end result is always a DOMDocument object.
* The casue is, that a \DOMElement object
* "is read only. It may be appended to a document,
* but additional nodes may not be appended to this node
* until the node is associated with a document."
* See {@link http://php.net/manual/en/domelement.construct.php here}).
*
* @param Ambigous <string, mixed> $elementName Used as element tagname. If it's not a string $defaultElementName is used instead.
* @param Ambigous <string, array> $elementContent
* @param Ambigous <\DOMDocument, NULL, \DOMElement> $parentNode The parent node is
* either a \DOMDocument (by the method calls from outside of the method)
* or a \DOMElement or NULL (by the calls from inside).
* Once again: For the calls from outside of the method the argument MUST be either a \DOMDocument object or NULL.
* @param string $defaultElementName If the key of the array element is a string, it determines the DOM element name / tagname.
* For numeric indexes the $defaultElementName is used.
* @return \DOMDocument
*/
protected function data2domNode($elementContent, $elementName, \DOMNode $parentNode = null, $defaultElementName = 'item') {
$parentNode = is_null($parentNode) ? new \DOMDocument('1.0', 'utf-8') : $parentNode;
$name = is_string($elementName) ? $elementName : $defaultElementName;
if (!is_array($elementContent)) {
$content = htmlspecialchars($elementContent);
$element = new \DOMElement($name, $content);
$parentNode->appendChild($element);
} else {
$element = new \DOMElement($name);
$parentNode->appendChild($element);
foreach ($elementContent as $key => $value) {
$elementChild = $this->data2domNode($value, $key, $element);
$parentNode->appendChild($elementChild);
}
}
return $parentNode;
}
}
答案 4 :(得分:0)
肯定必须有更快的方法来做到这一点
如果你已经安装了PEAR,那就有了。 Take a look XML_Seralizer。这是测试版,所以你必须使用
pear install XML_Serializer-beta
安装
答案 5 :(得分:0)
我需要一种能够转换具有非关联子阵列和需要使用CDATA(&lt;&gt;&amp;)转义的内容的数组的解决方案。由于我找不到任何合适的解决方案,我基于SimpleXML实现了自己的解决方案,这应该非常快。
https://github.com/traeger/SimplestXML(此解决方案支持(关联)数组=&gt; XML和XML =&gt;(关联)数组转换,不支持属性)。我希望这有助于某人。
答案 6 :(得分:0)
function combArrToXML($arrC=array(), $root="root", $element="element"){
$doc = new DOMDocument();
$doc->formatOutput = true;
$r = $doc->createElement( $root );
$doc->appendChild( $r );
$b = $doc->createElement( $element );
foreach( $arrC as $key => $val)
{
$$key = $doc->createElement( $key );
$$key->appendChild(
$doc->createTextNode( $val )
);
$b->appendChild( $$key );
$r->appendChild( $b );
}
return $doc->saveXML();
}
示例:
$b=array("testa"=>"testb", "testc"=>"testd");
combArrToXML($b, "root", "element");
输出:
<?xml version="1.0"?>
<root>
<element>
<testa>testb</testa>
<testc>testd</testc>
</element>
</root>