2015-09-28 87 views
1

我有一個XML文件,它有一個像下面這樣的結構:PHP的XPath選擇

<outfits> 
    <outfit name="1"></outfit> 
    <outfit name="2"></outfit> 
    <outfit name="3"></outfit> 
    <outfit name="4"></outfit> 
</outfits> 

現在我要選擇的每<outfit><outfits>標籤內。一直在嘗試使用以下PHP代碼。

$data = self::request($files['outfits']); //returns url from another function 
$data = @simplexml_load_string($data); // Loads the XML into a string from the URL 
$outfits = @$data->xpath('//outfits/*'); // Supposed to search the string using xpath 

UPDATE

功能看起來像真正執行以下操作:

public static function get_outfits($username){ 
    $files = self::user_files($username); 
    $data = self::request($files['outfits']); 
    $data = @simplexml_load_string($data); 
    if ($data && count(@$data->xpath('//outfit')) > 0){ 
     $outfits = @$data->xpath('//outfit'); 
     foreach($outfits as $outfit) { 
      $response['outfits'] = array(
       "name" => (string)$outfit['name'], 
       "color" => (string)$outfit['color'], 
       "mood" => (string)$outfit['mood'], 
       "species" => (string)$outfit['species'] 
      ); 
     } 
    } 
    else{ 
     echo 'User got no outfits.'; 
    } 
    return (isset($response) ? $response : false); 
    } 

但可悲的是他們的迴應始終是空的。有誰知道爲什麼?

+0

我認爲這是一個錯字,與它同樣的「問題」 –

+0

是的,對不起,這是一個錯字。更正它。 – d4nex

回答

3

xml被解析成一個對象,其中一個數組使用鍵「outfit」。

試試這個代碼,對我來說它的工作:使用XPath

$myXMLData = '<outfits> 
    <outfit name="1"></outfit> 
    <outfit name="2"></outfit> 
    <outfit name="3"></outfit> 
    <outfit name="4"></outfit> 
</outfits>'; 

$xml = simplexml_load_string($myXMLData); 
foreach ($xml->outfit as $outfit){ 
    echo $outfit['name']; 
} 

,你會得到:

$outfits = @$xml->xpath('//outfit'); 
print_r($outfits);