![](/img/trans.png)
[英]Having trouble understanding how to extract the data out of the result from a query
[英]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.