我正在尝试使用 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
,不带大括号。
最佳答案
不确定这是否是您正在寻找的,但它确实有效:)
$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"}]
关于PHP SimpleXML 到 JSON 编码单元素数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17773400/