如何使用PHP从json/xml中的@attributes获取数据

如何使用PHP从json/xml中的@attributes获取数据,php,json,xml,Php,Json,Xml,我在@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

我在@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);
下面是我使用上述代码得到的输出:

任何帮助都将不胜感激。谢谢。

@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;

您可以使用
简单xml
库附带的
属性
函数。它返回一个
simplexmlement
,它实现了
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);
}
?>

您可以将结果转换为数组,然后使用数组。请将此代码与我的代码同步?我该怎么做?出现以下错误:E_警告:类型2——非法字符串偏移量“@attributes”——在第6行异常:只有变量可以通过引用代码传递:$url=”http://synd.cricbuzz.com/j2me/1.0/livematches.xml"; $xml=simplexml_加载_文件($url)或死亡(“错误…”)$yourArray=json_encode($xml,true);提取($yourArray[“@attributes”]);echo$id这只是提供第一个匹配值,如何获取完整数据?
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/