simplexml_load_string似乎不起作用

时间:2016-01-11 13:32:24

标签: php xml

我使用此代码获取xml文件:

<?php
$username ="XXXX";
$password = "XXXX";
$url = 'XXXX';

$context = stream_context_create(array(
    'http' => array(
        'header'  => "Authorization: Basic " . base64_encode("$username:$password")
    )
));

$stringXML = file_get_contents($url, false, $context);
print_r($stringXML);
$stringXML = simplexml_load_string($stringXML);
echo "<br>";
print_r($stringXML);

我的XML看起来像:

<ns:getInfoResponse xmlns:ns="xxxx"> <ns:return> <result> <entry I_Personne="2291568592"> <loginGraceRemaining>10</loginGraceRemaining> <loginTime>20150827195311Z</loginTime> <loginDisabled>TRUE</loginDisabled> <isValidated>true</isValidated> <passwordExpirationTime>20160223195311Z</passwordExpirationTime> <mail_aai>xxxx.xxxx@xxxx.ch</mail_aai> </entry> </result> </ns:return> </ns:getInfoResponse> 

我的第二个print_r正在返回:SimpleXMLElement Object ( )

为什么它是空的?

1 个答案:

答案 0 :(得分:1)

您的问题的答案严格来说,您无法在SimpleXML对象上使用print_r获得有用的回复。

更有用的答案是你必须考虑命名空间和该命名空间的子节点。

由于您从文档中删除了命名空间URL,我将使用URL http://example.org/namespace/

替换命名空间

要获得条目的loginTime,您可以执行类似以下操作:

<?php
$stringXML = '<ns:getInfoResponse xmlns:ns="http://example.org/namespace/"> <ns:return> <result> <entry I_Personne="2291568592"> <loginGraceRemaining>10</loginGraceRemaining> <loginTime>20150827195311Z</loginTime> <loginDisabled>TRUE</loginDisabled> <isValidated>true</isValidated> <passwordExpirationTime>20160223195311Z</passwordExpirationTime> <mail_aai>xxxx.xxxx@xxxx.ch</mail_aai> </entry> </result> </ns:return> </ns:getInfoResponse>';

$xml = simplexml_load_string($stringXML);
$children = $xml->children("http://example.org/namespace/"); //loading the correct namespace and getting the children for it
echo (string)$children->{"return"}->children()[0]->children()[0]->loginTime;

请注意,可能有更好的方法可以找到正确的路径,特别是如果您有更复杂的文档。