簡體   English   中英

無法從xml中提取數據

[英]Having trouble to extract data from 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/這樣的東西

在此輸入圖像描述

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

你的問題是,匹配是一個匹配數組,你不能使用$ match ['type'],但必須迭代這樣的匹配:

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!

你通常使用錯誤的方法: -

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

當有重復的節點名稱(匹配)時,
它將呈現為對象列表(數組),
你不能只使用$xml->match
$xml->match[0], $xml->match[1] ...

至於屬性,你可以使用attributes()

無論如何,長話短說,使用xpath是更容易的解決方案

問題似乎在這里:

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

第一句話將為您提供一組符合您條件的元素。 您不能僅僅將比較應用為簡單變量。 您應該迭代返回的元素。 或者你應該應用一個過濾器來獲得那些屬性“type”為“ODI”的元素“匹配”。

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

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

您將$ mthType設置為數組,然后僅在匹配字符串時才返回它,這將永遠不會發生。 從第一個分配中刪除空的數組創建括號,這應該讓您走在正確的軌道上。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM