【问题标题】:How to get data from @attributes in json/xml with PHP如何使用 PHP 从 json/xml 中的@attributes 获取数据
【发布时间】:2017-04-04 14:11:39
【问题描述】:

我在 @attributes 中拥有所有 JSON 数据,并希望使用 PHP 将其提取到变量中。
我正在尝试什么:

$url = "http://synd.cricbuzz.com/j2me/1.0/livematches.xml";
$xml = simplexml_load_file($url) or die("Error..");
$json = json_encode($xml, JSON_PRETTY_PRINT);
$decode_json = json_decode($json);
$match = $decode_json->match[0];
print_r($match);

这是我使用上述代码得到的输出:http://phpfiddle.org/main/code/3zbq-62w0
任何帮助将不胜感激。谢谢..

【问题讨论】:

  • 可以将结果转为数组,然后使用数组

标签: php json xml


【解决方案1】:

您可以使用simple_xml 库附带的attributes 函数。它返回一个SimpleXMLElement,它实现了Traversable接口,这意味着你可以遍历:

<?php
$url = "http://synd.cricbuzz.com/j2me/1.0/livematches.xml";
$xml = simplexml_load_file($url) or die("Error..");
$match_attributes = $xml->match->attributes();

foreach ($match_attributes as $k => $v) {
    printf('%s => %s<br />', $k, $v);
}
?>

现在获取数据很容易。

id => 4
type => T20
srs => Bangladesh tour of Sri Lanka, 2017
mchDesc => SL vs BAN
mnum => 1st T20I
vcity => Colombo
vcountry => Sri Lanka
grnd => R.Premadasa Stadium
inngCnt => 1
datapath => http://synd.cricbuzz.com/j2me/1.0/match/2017/2017_SL_BAN/SL_BAN_APR04/

【讨论】:

  • 这里只提供第一个匹配值,如何获取完整数据...?
【解决方案2】:

@Sukhchain Singh 只需尝试以下一个:

<?php
    $yourArray = json_encode($yourJson, true);
    /* suppose you got $yourArray = array(
                            "@attributes" => array(
                            "id" => 4,
                            "type" => "T20",
                            "srs" => "Bangladesh tour of Sri Lanka, 2017",
                            "mchDesc" => "SL vs BAN",
                            "mnum" => "1st T20I",
                            "vcity" => "Colombo",
                            "vcountry" => "Sri Lanka",
                            "grnd" => "R.Premadasa Stadium",
                            "inngCnt" => 1,
                            "datapath" => "http://synd.cricbuzz.com/j2me/1.0/match/2017/2017_SL_BAN/SL_BAN_APR04/"
                        )
                    );
         */
extract($yourArray["@attributes"]); // it will extract all the element as a variable
echo $id;

【讨论】:

  • 您能将此代码与我的代码同步吗?我该怎么做?
  • 得到这个错误:E_WARNING : type 2 -- Illegal string offset '@attributes' -- at line 6 异常:只有变量可以通过引用传递代码:$url = "http://synd.cricbuzz.com/j2me/1.0/livematches.xml"; $xml = simplexml_load_file($url) or die("Error.."); $yourArray = json_encode($xml, true); extract($yourArray["@attributes"]); echo $id;
猜你喜欢
  • 1970-01-01
  • 2017-08-27
  • 1970-01-01
  • 1970-01-01
  • 2018-12-26
  • 1970-01-01
  • 2012-04-20
  • 2012-11-11
  • 2015-01-05
相关资源
最近更新 更多