在保留数组的同时使用PHP将XML转换为JSON

时间:2011-08-24 19:39:39

标签: php xml json simplexml

我需要将XML文档转换为JSON,以便轻松访问JavaScript中的数据。我目前正在使用此方法将XML转换为JSON:

json_encode(new SimpleXMLElement($xml, LIBXML_NOCDATA));

但是,当元素只包含1个子元素时,我遇到了问题。当使用SimpleXML解析它时,它被视为对象而不是数组。我希望它们始终被视为数组,除非元素只包含文本。

示例:

$xml = <<<END
<xml>
  <TESTS>
    <TEST>TEXT HERE</TEST>
  </TESTS>
</xml>
END;

echo json_encode(new SimpleXMLElement($xml, LIBXML_NOCDATA));

输出:

{"TESTS":{"TEST":"TEXT HERE"}}

如果我在下面添加另一个元素,那么输出就是我想要的:

$xml = <<<END
<xml>
  <TESTS>
    <TEST>TEXT HERE</TEST>
    <TEST>MORE TEXT HERE</TEST>
  </TESTS>
</xml>
END;

echo json_encode(new SimpleXMLElement($xml, LIBXML_NOCDATA));

输出:

{"TESTS":{"TEST":["TEXT HERE","TEXT HERE"]}}

注意元素是如何包含在JSON数组中而不是JSON对象中的。有没有办法强制元素被解析为数组?

2 个答案:

答案 0 :(得分:2)

我不得不处理同样的情况。这是问题的快速第一解决方案 - 适用于您的示例。

class JsonWithArrays
{
    protected $root, $callback;

    public function __construct( SimpleXMLElement $root )
    {
        $this->root = $root;
    }

    /**
     * Set a callback to return if a node should be represented as an array
     * under any circumstances.
     *
     * The callback receives two parameters to react to: the SimpleXMLNode in
     * question, and the nesting level of that node.
     */
    public function use_callback_forcing_array ( $callback )
    {
        $this->callback = $callback;
        return $this;
    }

    public function to_json ()
    {
        $transformed = $this->transform_subnodes( $this->root, new stdClass(), 0 );
        return json_encode( $transformed );
    }

    protected function transform_subnodes ( SimpleXMLElement $parent, stdClass $transformed_parent, $nesting_level )
    {
        $nesting_level++;

        foreach( $parent->children() as $node )
        {
            $name = $node->getName();
            $value = (string) $node;

            if ( count( $node->children() ) > 0 )
            {
                $transformed_parent->$name = new stdClass();
                $this->transform_subnodes( $node, $transformed_parent->$name, $nesting_level );
            }
            elseif ( count( $parent->$name ) > 1 or $this->force_array( $node, $nesting_level ) )
            {
                $transformed_parent->{$name}[] = $value;
            }
            else
            {
                $transformed_parent->$name = $value;
            }
        }

        return $transformed_parent;
    }

    protected function force_array ( $node, $nesting_level )
    {
        if ( is_callable( $this->callback ) )
        {
            return call_user_func( $this->callback, $node, $nesting_level );
        }
        else
        {
            return false;
        }
    }
}

$xml = <<<END
<xml> 
  <TESTS> 
    <TEST>TEXT HERE</TEST> 
  </TESTS> 
</xml> 
END;

$xml2 = <<<END
<xml> 
  <TESTS> 
    <TEST>TEXT HERE</TEST> 
    <TEST>MORE TEXT HERE</TEST> 
  </TESTS> 
</xml> 
END;

// Callback using the node name. Could just as well be done using the nesting
// level.
function cb_testnode_as_array( SimpleXMLElement $node, $nesting_level )
{
    return $node->getName() == 'TEST';
}

$transform = new JsonWithArrays( new SimpleXMLElement($xml, LIBXML_NOCDATA) );
echo $transform
    ->use_callback_forcing_array( 'cb_testnode_as_array' )
    ->to_json();

echo PHP_EOL;

$transform2 = new JsonWithArrays( new SimpleXMLElement($xml2, LIBXML_NOCDATA) );
echo $transform2
    ->use_callback_forcing_array( 'cb_testnode_as_array' )
    ->to_json();

答案 1 :(得分:0)

echo json_encode(json_decode(json_encode(new SimpleXMLElement($xml, LIBXML_NOCDATA)), true));

真的这很愚蠢,但你首先如果所有转换为对象然后在数组中解码并转换为json像数组样式..))