我使用xml格式的cURL检索一些信息.
....
$xml = curl_exec($ch);
$data = simplexml_load_string($xml);
print_r($data);
//out put - SimpleXMLElement Object ( )
如果我尝试 – print_r($xml);并查看页面源
我明白了
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns7:users xmlns="http://www.example.com/xml/ns/rs"
xmlns:ns2="http://www.example.com/xml/ns/users"
xmlns:ns3="http://www.example.com/2004/11/tHistory"
xmlns:ns4="http://www.example.com/fsi/tHistory"
xmlns:ns5="http://www.example.com/2005/10/tHistory"
xmlns:ns6="http://www.example.com/2010/03/cs"
xmlns:ns7="http://www.example.com/2005/10/users"
xmlns:ns8="http://www.example.com/2010/03/tHistory">
<ns7:user><ns7:id>Matt.Smith</ns7:id>
<ns7:lastName>Smith</ns7:lastName>
<ns7:firstName>Matt</ns7:firstName>
<ns7:otherName></ns7:otherName>
<ns7:gender>male</ns7:gender>
<ns7:email>matt@company.co.uk</ns7:email>
<ns7:locale>en</ns7:locale>
<ns7:role><ns7:id>A</ns7:id>
<ns7:name>System Administrator</ns7:name></ns7:role>
<ns7:employeeNumber></ns7:employeeNumber>
<ns7:organization>
<ns7:id>8000</ns7:id>
<ns7:name>Organisation Title</ns7:name>
</ns7:organization>
<ns7:organization>
<ns7:id>20707</ns7:id>
<ns7:name>London Office</ns7:name>
</ns7:organization>
<ns7:attribute>
<ns7:code>0</ns7:code>
<ns7:description>Unassigned</ns7:description>
</ns7:attribute>
<ns7:attribute>
<ns7:code>0</ns7:code>
<ns7:description>Unassigned</ns7:description>
</ns7:attribute>
<ns7:attribute>
<ns7:code></ns7:code>
<ns7:description>Unassigned</ns7:description>
</ns7:attribute>
<ns7:attribute>
<ns7:code></ns7:code>
<ns7:description>Unassigned</ns7:description></ns7:attribute>
<ns7:attribute><ns7:code></ns7:code>
<ns7:description>Unassigned</ns7:description>
</ns7:attribute>
<ns7:attribute>
<ns7:code></ns7:code>
<ns7:description>Unassigned</ns7:description>
</ns7:attribute>
<ns7:attribute>
<ns7:code></ns7:code>
<ns7:description>Unassigned</ns7:description>
</ns7:attribute>
<ns7:attribute>
<ns7:code></ns7:code>
<ns7:description>Unassigned</ns7:description>
</ns7:attribute>
</ns7:user>
</ns7:users>
这个xml全部在一行中,我手动输入了换行符,使其可读.
解决方法:
更新:要打印firstname(或任何其他),您可以使用the usual SimpleXML addressing mechanisms.您的情况稍微复杂一点,因为您正在使用名称空间.仍然可行 – 尝试一些like this:
$data->children('ns7', true)->user[0]->lastName
re:我期待print_r($data)打印就好像它是一个数组[…]:这种期望是错误的.它肯定会很方便,但这不是它的工作原理.要打印SimpleXML对象的xml字符串表示形式,请使用asXML()
.
更新结束
你期望print_r($data)打印什么? SimpleXMLElement Object()似乎是完全有效的输出给我.这并不意味着xml有问题.如果要查看SimpleXMLElement对象的实际xml,请尝试print $data-> asXML().