2

I am trying to parse xml with php into a single element json array.

This is what I have:

$t = array();

$a=array("url"=>$test->channel->item->link);
array_push($t,$a);
echo json_encode($t);;

Which gives me this:

[{"url":{"0":"http:www.example.com"}}]

But I am looking for this:

[{"url":"http:www.example.com"}]

It seems that $test->channel->item->link parses with curly brackets as {url}

but if I do echo $test->channel->item->link, I get: www.example.com without the curly brackets.

2
  • Why are you doing $a = array() and not just $t[] = array()? Commented Jul 21, 2013 at 14:41
  • This is a stripped version of what I am using. the $a = array() doesn't even exists. It's for this example Commented Jul 21, 2013 at 14:43

2 Answers 2

1

Not sure if this is what you're looking for, but it works :)

$xmlstr = '<?xml version=\'1.0\' standalone=\'yes\'?>
      <container>
        <channel>
          <item>
            <link>www.example.com</link>
          </item>
        </channel>
      </container>';

$test = new SimpleXMLElement($xmlstr);

$t = array();
$a = array("url"=>$test->channel->item->link->__toString());
array_push($t,$a);
echo json_encode($t); // [{"url":"www.example.com"}]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I was using toString the wrong way. I think I should stop mixing js with php :)
1

Check out this implementation, this is working for me.

class eg{
    public $link;
    function __construct()
    {
        $this->link = "www.myweb.com";
    }
}

class eg1{
    public $item;
    function __construct()
    {
        $this->item = new eg();
    }
}

class eg2{
    public $channel;
    function __construct()
    {
        $this->channel = new eg1();
    }
}

$test = new eg2();

$t = array();

$a=array("url"=>$test->channel->item->link);
array_push($t,$a);
echo json_encode($t);

And this will render the following string

[{"url":"www.myweb.com"}]

Comments

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.