我试图解析服务器的响应,但是我在努力获取所需的信息。我正在尝试解析用户名和用户名1234,并将其保存到变量中,但是我无法正确解析它,并且不确定自己在做什么错。
通过使用cUrl
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $cas_url);
curl_setopt($ch, CURLOPT_SSLVERSION, 6);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
echo nl2br("\nReply from curl: ").htmlentities($response);
curl_close( $ch );
或file_get_contents
$resp = file_get_contents(htmlentities($cas_url));
我得到以下信息:
<cas:serviceResponse xmlns:cas='http://somesite.edu'>
<cas:authenticationSuccess> <cas:user>username1234</cas:user>
</cas:authenticationSuccess> </cas:serviceResponse>
我试图使用DOM解析它,将上面的回复保存到$ xml,但它什么也没有返回。
$dom = new DomDocument();
$dom->loadXML($xml);
$xpath = new DomXPath($dom);
$node = $xpath->query("//cas:user");
if ($node->length) {
echo $node[0]->textContent;
}
我也尝试过registerXPathNamespace,因为我注意到它用xmlns进行了答复,但是我确定我做错了:
$XML_Obj = new SimpleXMLElement($response);
$XML_Obj -> registerXPathNamespace('cas','http://www.yale.edu/tp/cas');
foreach($XML_Obj->xpath('//cas:user') as $event){
var_export($event->xpath('cas:serviceResponse'));
}
答案 0 :(得分:1)
不要在输出中调用htmlentities()
,仅当您要在浏览器中显示它时才需要。如果要作为原始XML处理,则不需要这样做。在这种情况下,your first example可以正常工作。
$xml = file_get_contents($cas_url);
$dom = new DomDocument();
$dom->loadXML($xml);
$xpath = new DomXPath($dom);
$node = $xpath->query("//cas:user");
if ($node->length) {
echo $node[0]->textContent;
}