質問

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.

役に立ちましたか?

解決

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"}]

他のヒント

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"}]
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top