这是一个示例项目:
SimpleXMLElement Object
(
[@attributes] => Array
(
[displayInfoId] => 62116
[durability] => 100
[gem0Id] => 41401
[gem1Id] => 40123
[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 :(得分: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 =&gt; value)对。
答案 1 :(得分:2)
这个怎么样
$jsonArray = array();
foreach ($xmlObj->attributes() as $attr => $value) {
$jsonArray[$attr] = (string)$value;
}
$jsonString = json_encode($jsonArray);
编辑:您也可以使用
$jsonString = json_encode($xmlObj->attributes());
但是我不确定属性值是作为字符串还是对象返回(编辑 - 结果你不能。请参阅Artefacto的解决方案)。
答案 2 :(得分:1)
这个怎么样?
$array = (array)$simplexml->node->attributes();
$jsonArray = json_encode($array['@attributes']);