2014-03-25 45 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

终于在工作!非常感谢。 :) –