Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6476867
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T06:52:41+00:00 2026-05-25T06:52:41+00:00

I need to convert an XML document into JSON, in order to easily access

  • 0

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?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T06:52:42+00:00Added an answer on May 25, 2026 at 6:52 am

    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();
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm currently working on a Silverlight app and need to convert XML data into
I need to convert an xml document into json in jquery but without plugin
I have an xml document object that I need to convert into a string.
I need to Convert a CSV into an XML document. The examples I have
I have an XML Document and I need to convert it into an Excel
I need to convert HTML documents into valid XML, preferably XHTML. What's the best
I am in a need of programatically convert an Word-XML file into a RTF
I need to convert default mysql modtimes into UTC formated datetimes using xslt. I
i'm trying to convert my log4j.properties into log4j.xml because i need to use some
I need to convert XML built with dom4j to a w3c document and don't

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.