将SimpleXMLElement转换为JSON数组

时间:2014-08-01 11:53:19

标签: php arrays xml json loops

我有一个存储过程(SQL Server),它返回以下XML,这是给定月份的搜索词排名前20位。 使用以下PHP,我可以获取此XML并循环遍历它:

foreach ($objSearchTerms->searchTerms as $terms){ echo $terms->searchTerm; };

提取工作并返回正确的数据。但是,我的问题是我需要创建一个类似于下面的数组,以便在JS中使用。

谁能告诉我如何实现这一目标? 数组的文本部分将是我的搜索术语($terms->searchTerm),权重只是从20到0的反向计数。

我的simpleXML:

<ranks>
  <searchTerms>
    <rank>1</rank>
    <searchTerm>item 1</searchTerm>
    <volume>11</volume>
  </searchTerms>
  <searchTerms>
    <rank>2</rank>
    <searchTerm>item 2</searchTerm>
    <volume>8</volume>
  </searchTerms>
  <searchTerms>
    <rank>3</rank>
    <searchTerm>item 3</searchTerm>
    <volume>5</volume>
  </searchTerms>
  // ...
</ranks>

预期结果:

var word_array = [
    {text: "item 1", weight: 20},
    {text: "item 2", weight: 19},
    {text: "item 3", weight: 18},
    // ...
];

我尝试了类似以下的内容,但这不起作用,可能不是正确的方法:

$count = 21;
foreach ($objSearchTerms->searchTerms as $terms){ 
    $count--;
    echo "{text: '" . $terms->searchTerm . "', weight: " . $count . "},";
}

1 个答案:

答案 0 :(得分:1)

此代码可以帮助您

$xml = simplexml_load_file("file.xml");
$result = [];
$count = 20;
foreach ($xml->searchTerms as $value) 
{
    $child = [];
    $child['text'] = (string)$value->searchTerm;
    $child['weight'] = $count--;
    $result[] = $child;
}
$json_string = json_encode($result);

我得到的结果是

[
    {"text":"item 1","weight":20},
    {"text":"item 2","weight":19},
    {"text":"item 3","weight":18}
]