简体   繁体   中英

Having trouble to extract data from xml

i am trying to grab data from xml, but having issues.

I have create simple codes but i don't think they are going well..

<?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;
        }

    }
?>

and calling as

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

but i am unable to fetch results.

Please help me to solve this issue. I am trying make a something like http://www.hamariweb.com/

在此输入图像描述

please help me to solve this .. thank you all

Your problem is that as match is an array of matches, you cannot use $match['type'] but have to iterate over matches like this:

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

Also you don't need the curl. If there is no reason, you can always use the data_is_url and then give the SimpleXMLElement the url!

You have using wrong method for this,in general :-

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

When there are repeated node name (match),
it will render as list of objects (array),
you can't just use $xml->match ,
but $xml->match[0], $xml->match[1] ...

as for the attribute, you can use attributes()

anyway, long story short, use the xpath is the easier solution

The problem seems to be here:

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

The first sentence will give you a set of elements matching your condition. You can not just apply a comparison as if it were a simple variable. You should iterate the returned elements. Or you should apply a filter to get just those elements "match" whose attribute "type" is "ODI".

The problem is not with your XML parsing, it's with your $mthType checking, specifically these two lines:

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

You're setting $mthType up as an array, then only returning it if it matches a string, which will never happen. Remove the empty array-creation brackets from the first assignment, and that should put you on the right track.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM