2011-12-09 101 views
0

我想從xml獲取數據,但遇到問題。無法從xml提取數據

我已創建簡單的代碼,但我不認爲他們會好..

<?php 
    $cricapi = 'http://synd.cricbuzz.com/j2me/1.0/livematches.xml'; 

    function followers($url) { 
     $ch = curl_init(); 
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
     curl_setopt($ch, CURLOPT_URL, $url); 
     $data = curl_exec($ch); 
     curl_close($ch); 

     $xml = new SimpleXMLElement($data); 
     $mthType = $xml->match['type']; 
     if ($mthType == "ODI") 
     { 
      $match = $xml->match['mchDesc']; 
      return $match; 
     } 

    } 
?> 

,並呼籲爲

<?php echo $match = followers($cricapi); ?> 

,但我無法獲取結果。

請幫我解決這個問題。我試圖做一個類似http://www.hamariweb.com/

enter image description here

請幫我解決這個問題..謝謝大家

+0

確切的問題是什麼? 「但我無法取得結果」不是一個具體問題。 – jli

+0

請嘗試運行此腳本..我應用條件,如果類型== ODI然後提取匹配說明,但該腳本只檢查第一種類型,不要再運行..即使我嘗試foreach循環:( – Muzammil

+0

)你嘗試使用data_is_url標誌而不是curl嗎?嘗試'$ xml = new SimpleXMLElement($ url,0,true);'只用於檢索xml。 – Sgoettschkes

回答

-1

的問題不在於你的XML解析,它與你的$ mthType檢查,特別是這些兩行:

$mthType[] = $xml->match['type']; 
if ($mthType == "ODI") 

你設置$ mthType了一個數組,然後只有當它的字符串,這將永遠不會發生匹配返回它。從第一個作業中刪除空的數組創建括號,這應該使你走上正確的軌道。

$mthType = $xml->match['type']; 
if ($mthType == "ODI") 
+0

對不起,我錯誤地輸入了,但是我也嘗試這種方式tooo ..但同樣的迴應:( – Muzammil

+0

有時你必須顯式地給(字符串)數據類型在處理SimpleXML的結果時試試這行:$ mthType =(string)$ xml-> match ['鍵入'];或者,在另一個答案中使用xpath,這將是首選的 –

0

這個問題似乎是在這裏:

$mthType[] = $xml->match['type']; 
if ($mthType == "ODI") { 
    ... 
} 

第一句會給你一套符合條件的元素。 你不能僅僅應用一個比較就好像它是一個簡單的變量。你應該迭代返回的元素。或者你應該應用一個過濾器來獲得那些屬性「type」是「ODI」的元素「匹配」。

1

您已經使用了這種錯誤的方法,一般來說: -

$found = $xml->xpath("//match[@type='ODI']"); 
// is an array of collection that with node name is match, and attribute type=ODI 

當有重複的節點名稱(匹配),
它會呈現爲對象列表(陣列),
可以「T只使用$xml->match
$xml->match[0], $xml->match[1] ...

爲屬性,你可以使用attributes()

無論如何,長話短說,使用xpath是簡單的解決方案

+0

我沒有清楚的理解..你可以請描述一下 – Muzammil

+0

已經解釋了,我建議你先做一些閱讀 – ajreal

+0

謝謝非常多..:D – Muzammil

2

你的問題是,比賽是比賽的一個數組,你不能使用$匹配[「型」],但必須遍歷這樣的比賽:

function followers($url) { 
    $xml = new SimpleXMLElement($url,1,true); 
    foreach($xml->match AS $match){ 
    if($match['type']== "ODI"){ 
     echo $match['mchDesc']; 
    } 
    } 
} 

你也不需要捲曲。如果沒有理由,你可以隨時使用data_is_url,然後給SimpleXMLElement的URL!