将XML对象与字符串进行比较

时间:2014-03-25 15:59:08

标签: php xml string object

我正在尝试将对象转换为字符串并进行比较,但它无法正常工作。

有人能看到问题吗?

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 个答案:

答案 0 :(得分:0)

您的XML在id值周围有空格,这可能是比较失败的原因。

你应该在比较之前修剪字符串:

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