2015-09-27 56 views
1

我正在PHP中進行用戶Basic Auth驗證,並通過XML文件獲取驗證結果,然後將該文件解析爲PHP變量。PHP中的XML解析不捕獲一個變量

這裏是PHP代碼:

<?php 

$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING); 
$password = filter_var($_POST['password'], FILTER_SANITIZE_STRING); 
$str = $username . ":" . $password; 
$client_id = md5($str); 
$auth_str = base64_encode($str); 
$client_id_str = "client-identifier: " . $client_id; 
$plex_auth = "authorization: Basic " . $auth_str; 

$curl = curl_init(); 

curl_setopt_array($curl, array(
    CURLOPT_URL => "https://someurl/sign_in.xml", 
    CURLOPT_RETURNTRANSFER => true, 
    CURLOPT_ENCODING => "", 
    CURLOPT_MAXREDIRS => 10, 
    CURLOPT_TIMEOUT => 30, 
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, 
    CURLOPT_CUSTOMREQUEST => "POST", 
    CURLOPT_HTTPHEADER => array(
     $plex_auth, 
     $client_id_str, 
     "header3", 
     "header4" 
    ), 
)); 

$response = curl_exec($curl); 

$xml = simplexml_load_string($response); 

$err = curl_error($curl); 

curl_close($curl); 

if ($err) { 
    echo "cURL Error #:" . $err; 
} else { 
    echo $response; 
} 

$user_token = $xml->authenticationtoken; 
$user_email = $xml->email; 

echo $user_email; 
echo $user_token; 

?> 

這是在XML響應:

<?xml version="1.0" encoding="UTF-8"?> 
<user email="[email protected]" id="2567053" 
    thumb="https://secure.gravatar.com/avatar/somenumber" 
    username="Admin" title="Admin" cloudSyncDevice="" 
    authenticationToken="SomeToken" scrobbleTypes=""> 
    <subscription active="1" status="Active" plan="lifetime"> 
     <feature id="pass"/> 
     <feature id="sync"/> 
     <feature id="cloudsync"/> 
     <feature id="home"/> 
    </subscription> 
    <profile_settings auto_select_audio="1" auto_select_subtitle="0" 
     default_audio_language="en" default_subtitle_language="en"/> 
    <username>Admin</username> 
    <email>[email protected]</email> 
    <joined-at type="datetime">2014-05-08 17:59:24 UTC</joined-at> 
    <authentication-token>SomeToken</authentication-token> 
</user> 

現在,出於某種原因,而我可以從XML中提取所有其他變量,那麼authenticationToken拒絕得到解析。當我回應user_token時,它完全是空的!

回答

1

據對SimpleXML PHP的文檔的例子:

包含下PHP的命名約定不允許(例如連字符)字符的XML文檔中訪問元件可以通過支架和內封裝所述元件名稱來完成撇號。

這樣你就可以像這樣訪問:

$user_token = $xml->{'authentication-token'}; 
0

您提供的不似乎是一個有效的XML字符串XML響應。 我無法解析它,直到我在'user'標記的末尾添加'>'。 此外,如我之前的答覆中提到,你將需要訪問包含與護腕和單qoutes特殊字符對象屬性:

$user_token = $xml->{'authentication-token'}; 

或像這樣:

$auth_token = 'authentication-token'; 
$user_token = $xml->$auth_token;