2010-11-03 66 views
3

这是一个例子项目:问题的SimpleXML解析WoWArmory属性

SimpleXMLElement Object 
(
    [@attributes] => Array 
     (
      [displayInfoId] => 62116 
      [durability] => 100 
      [gem0Id] => 41401 
      [gem1Id] => 4
      [gem2Id] => 0 
      [gemIcon0] => inv_jewelcrafting_shadowspirit_02 
      [gemIcon1] => inv_jewelcrafting_gem_37 
      [icon] => inv_helmet_98 
      [id] => 48592 
      [level] => 245 
      [maxDurability] => 100 
      [name] => Liadrin's Headpiece of Triumph 
      [permanentEnchantIcon] => ability_warrior_shieldmastery 
      [permanentEnchantItemId] => 44876 
      [permanentenchant] => 3819 
      [pickUp] => PickUpLargeChain 
      [putDown] => PutDownLArgeChain 
      [randomPropertiesId] => 0 
      [rarity] => 4 
      [seed] => 0 
      [slot] => 0 
     ) 

) 

我试图让每个项目一个JSON对象,但有大约17什么的,如果我尝试json_encode()它给我“@attributes”作为包含我想要的所有东西的对象。帮帮我?

+0

对不起,我有点困惑,如果这是php代码,那么逗号分隔键 - 值对的地方在哪里?和终结者分号?你从哪里得到这个? – 2010-11-03 00:11:56

+0

@Michael看起来像SimpleXML对象的'print_r' – Phil 2010-11-03 00:13:14

+0

是的,我试图从SimpleXML对象获取JSON对象。 – 2010-11-03 00:14:40

回答

2

这个怎么样

$jsonArray = array(); 
foreach ($xmlObj->attributes() as $attr => $value) { 
    $jsonArray[$attr] = (string)$value; 
} 

$jsonString = json_encode($jsonArray); 

编辑:您可能还可以简单地使用

$jsonString = json_encode($xmlObj->attributes()); 

但是我不知道如果属性值作为字符串或对象(编辑返回 - 事实证明你不能,看到Artefacto的解决方案)。

+0

您的编辑解决方案不起作用;看到我的答案。 – Artefacto 2010-11-03 00:24:47

1

这个怎么样?

$array = (array)$simplexml->node->attributes(); 
$jsonArray = json_encode($array['@attributes']); 
6

事情是这样的:

<?php 
$sxm = new SimpleXMLElement("<a name=\"kkk\" other=\"foo\"/>"); 
$attrs = $sxm->attributes(); 
var_dump(json_encode(reset($attrs))); 

给出:

 
string(28) "{"name":"kkk","other":"foo"}" 

您所遇到的问题是,因为$xmlObj->attributes()返回SimpleXMLElement,当转换为一个数组,是一个数组关键字“@attributes”和一个实际上具有属性(name => value)对的数组的值。

+0

+1但是不需要'attributes()'调用。你可以直接在元素上使用'reset()'。也就是说,使用它可以更安全*确保属性是数组中的第一个元素。 – 2010-11-03 00:29:47

+0

'reset'在对象上不起作用(这是'$ sxm'或'$ sxm-> attributes()'返回的)。您必须首先将其转换为数组。我相信这是5.3中改变的行为。 – netcoder 2010-11-03 00:34:15

+0

@netcoder也许我在这里有5.3。 – 2010-11-03 00:37:15