2010-04-16 49 views
1

我是PHP的初學者。我試圖解析這個XML文件。PHP:用簡單的XML需要他!p

<relationship> 
<target> 
    <following type="boolean">true</following> 
    <followed_by type="boolean">true</followed_by> 
    <screen_name>xxxx</screen_name> 
    <id type="integer">xxxx</id> 
</target> 
<source> 
    <notifications_enabled nil="true"/> 
    <following type="boolean">true</following> 
    <blocking nil="true"/> 
    <followed_by type="boolean">true</followed_by> 
    <screen_name>xxxx</screen_name> 
    <id type="integer">xxxxx</id> 
</source> 
</relationship> 

我需要的字段的值「以下類型=‘布爾’」爲目標,這裏是我的代碼 -

$xml = simplexml_load_string($response); 

foreach($xml->children() as $child) 
{ 
     if ($child->getName() == 'target') 
     { 
     foreach($child->children() as $child_1) 
     if ($child_1->getName() == 'following') 
     { 
     $is_my_friend = (bool)$child_1; 
     break; 
     } 
     break; 
     } 
} 

,但我沒有得到正確的輸出。我認爲該字段的'type =「boolean」'部分會產生問題。請幫忙。

+0

你會得到什麼? – mauris 2010-04-16 03:57:47

+0

我得到0作爲輸出 – Bruce 2010-04-16 04:03:06

回答

4

您也可以使用xpath

foreach ($xml->xpath("//target/following[@type='boolean']") as $is_my_friend) 
{ 
    echo $is_my_friend; 
} 
2

$ xml = simplexml_load_string($ response);

foreach($ xml-> target-> following as $ child) { $ is_my_friend = $ child; }