2014-03-25 42 views
0

我試圖將一個對象轉換爲字符串並比較它們,但它不工作。比較XML對象和字符串

任何人都可以看到問題嗎?

Hello <?php $country = (string)$_POST["country"]; echo $country; ?><br> 
<? 
    //echo gettype($country), "\n"; 
    $xml=simplexml_load_file("info.xml"); 

    foreach($xml->children() as $xml_country){ 
     //echo $xml_country->id . ": " . "<br>"; 

     //$id = array((string) $xml_country->id); 
     $id = strip_tags($xml_country->id->asXML()); 
     echo $id; 
     echo "id: ", gettype($id), "\n"; 
     echo "country: ", gettype($country), "\n"; 
     echo "\n"; 
     if($country == $id){ 
      echo $xml_country->id . ": " . "<br>"; 
     } 
    } 
    ?> 

Info.xml

<countries> 

<country> 
    <id> AF </id> 
    <name> Afghanistan </name> 
    <city> 
     Major cities - population: KABUL (capital) 3.097 million (2011) 
    </city> 
    <description> 
     This entry provides the population of the capital and up to four major cities defined as urban agglomerations with populations of at least 750,000 people. 
    </description> 
    <hiv> 
     Adult prevalence rate: 0.01% (2001 est.) 
    </hiv> 
</country> 
</countries> 

輸出

http://i.gyazo.com/261c6892ef8b6bf8fbdf5d3a7303ebef.png

+1

什麼是你的腳本輸出目前,又是什麼內容info.xml是什麼樣子? –

+0

@BrianDriscoll請參閱編輯。 –

+0

好的,你期望的輸出是什麼?你應該知道'=='做了一個鬆散的類型比較,所以你不需要使用該運算符來比較兩個字符串。 –

回答

0

你的XML有各地的ID值,這可能是爲什麼比較失敗的原因空白。

你應該比較之前總是修剪字符串:

if(trim($country) == trim($id)){ 
     echo $xml_country->id . ": " . "<br>"; 
    } 
+0

終於在工作!非常感謝。 :) –