2017-04-04 86 views
-2

我擁有@attributes中的所有JSON數據,並希望使用PHP將其提取到變量。
我努力:如何從@attributes獲取json/xml中的數據與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
任何幫助將不勝感激。謝謝..

+1

你可以將結果轉換爲數組,然後使用數組 –

回答

-1

@Sukhchain辛格只是嘗試以下之一:

<?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; 
+0

你能同步這段代碼與我的代碼嗎?我怎樣才能做到這一點? –

+0

檢查得到這個錯誤更新的一個 –

+0

: E_WARNING:2型 - 非法串偏移「@屬性」 - 第6行 例外:只有變量可以通過引用傳遞 代碼: '$ URL =「HTTP: //synd.cricbuzz.com/j2me/1.0/livematches.xml「; $ xml = simplexml_load_file($ url)或die(「Error ..」); $ yourArray = json_encode($ xml,true); 提取($ yourArray [「@ attributes」]); echo $ id;' –

1

您可以使用自帶的simple_xmlattributes功能。它返回一個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/ 
+1

謝謝:)這真的幫了我很多! –

+0

這只是提供第一個匹配值,如何獲得完整的數據......? – Srinivas08