0

How do I parse the following

{menu id="123"}
  Random text.
  {menu-item id="123"/}
  Random text.
  {menu-item id="123"/}
{/menu}

into an array, like such

Array(
  [menu] => Array(
    [id] => 123
    [children] => Array(
      [menu-item] = Array(
        [id] => 123
      )
      [menu-item] = Array(
        [id] => 123
      )
    )
  )
)

It's similar to HTML. Tags that do not have a closing tag are self-closed.

5
  • you should format your string before parse it..see the JSON syntax Commented Mar 21, 2013 at 7:46
  • 2
    What have you tried? Commented Mar 21, 2013 at 7:46
  • @Sudip Pal, code cannot be in JSON syntax. Commented Mar 21, 2013 at 7:52
  • Without JSON, you should manually break it with explode() as a string and push it to array...that's the limit.. Commented Mar 21, 2013 at 7:54
  • @Tushar I've done it the preg_match way, but I'd like to learn a better way. Commented Mar 21, 2013 at 7:55

1 Answer 1

2

Mmh - if this is like html you could try and treat it like XML and use simplexml.

Lets give it a try:

$xmlData = str_replace( array( '{', '}' ), array( '<', '>' ), $sourceData );
$xmlObj = simplexml_load_string( $xmlData );

var_dump( $xmlObj );

The resulting object might not be 100% of the structure you are trying to form, but now that's already much easier to achieve.

Looking forward to your feedback, Have fun!

Sign up to request clarification or add additional context in comments.

2 Comments

That is a great idea! Will try.
You'll actually have to deal with the text which is not in own tags - either wrap it into tags or remove it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.