2

我正在尝试用 php 将 xml 解析为单个元素 json 数组。

这就是我所拥有的:

$t = array();

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

这给了我这个:

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

我正在寻找这个:

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

似乎$test->channel->item->link用大括号解析为{url}

但如果我这样做echo $test->channel->item->link,我会得到:www.example.com没有大括号。

4

2 回答 2

1

不确定这是否是您正在寻找的,但它有效:)

$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"}]
于 2013-07-21T14:52:53.567 回答
1

看看这个实现,这对我有用。

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

这将呈现以下字符串

[{"url":"www.myweb.com"}]
于 2013-07-21T14:46:33.487 回答