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

发布于 2024-12-01 15:17:21 字数 973 浏览 0 评论 0原文

我需要将 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 对象内。有没有办法强制将元素解析为数组?

I need to convert an XML document into JSON, in order to easily access the data in JavaScript. I am currently using this method to convert the XML into JSON:

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

However, I ran into a problem when an element only contains 1 child element. When it is parsed with SimpleXML, it is treated as an object instead of an array. I want them to always be treated as arrays, unless the element only contains text.

Example:

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

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

This outputs:

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

If I add another element under , then the output is how I want it:

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

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

Output:

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

Note how the elements are contained inside a JSON array instead of a JSON object. Is there a way to force elements to be parsed as arrays?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

遥远的绿洲 2024-12-08 15:17:21

我不得不处理同样的情况。这是问题的第一个快速解决方案 - 对于您的示例来说效果很好。

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();

I had to deal with the same situation. Here is a quick first solution to the problem - works fine for your example.

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();
尐偏执 2024-12-08 15:17:21
echo json_encode(json_decode(json_encode(new SimpleXMLElement($xml, LIBXML_NOCDATA)), true));

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

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

Really this is lot a stupid but you first if all convert to object then decode in array and convert to json like array style.. ))

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文