如何在PHP中使用数组获取值元素[@attributes]

时间:2017-02-04 10:22:27

标签: php arrays xml

<function name="getMemberInfo">
    <component name="people">
        <property name="ppl_firstname">
            <![CDATA[ Jamie ]]>
        </property>
    </component>
</function>

我正在尝试检索ppl_firstname。上面的XML showend是已经由API url解析的代码的一部分。

我使用curl获取网址内容

$url=""
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);    // get the url contents
$data = curl_exec($ch); // execute curl request
curl_close($ch);

然后我将数据放入数组

$xml = simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
$xmlJson = json_encode($xml);
$xmlArr = json_decode($xmlJson, 1); // Returns associative array

输出如下:

Array ( [@attributes] => 
    Array ( [name] => getMemberInfo ) [component] => 
        Array ( [0] => 
            Array ( [@attributes] => 
                Array ( [name] => people ) [property] => 
                    Array ( [0] => Jamie [1] )
                  )
              )
       )

任何人都可以告诉我如何检索名称。提前致谢

1 个答案:

答案 0 :(得分:0)

您要做的是首先访问孩子property然后您可以访问此孩子的属性。

$xml_string = '<function name="getMemberInfo">
                     <component name="people">
                          <property name="ppl_firstname">
                               <![CDATA[ Jamie ]]>
                          </property>
                     </component>
                 </function>';
$function = simplexml_load_string($xml_string);
$component= $function->children();
//access your property children
$property = $component->children();
$property_name = $property->attributes()->name;
//check if it prints the right name
echo "Property name: ".$property_name