2012-11-12 60 views
2

我剛剛學習PHP。我有一堆我已經開始的腳本,有一個讓我卡住了。我正在獲取一個xml並將結果打印到頁面上。但是,我只想要refTypeID = 10的行,並且還需要將原因區域中的文本「DESC:」修剪掉。解析XML和回顯結果

我當前的代碼

<?php 

// Populate the following with your API Data 
$vCode = "XXXXXXX"; 
$keyID = "XXXXXXX"; 

// Create the URL to the EVE API 
$eveAPI = "http://api.eve-online.com/corp/WalletJournal.xml.aspx?keyID=".$keyID."&vCode=".$vCode.""; 

// Get the xml data 
$xml = simplexml_load_file($eveAPI); 

// Loop Through Skills 
foreach ($xml->result->rowset->row as $value) { 
    echo "Skill Number:".$value['refTypeID']." -- Skill Points: ".$value['ownerName1']." -- Level: ".$value['reason']."<br />"; 
}; 

?> 

什麼我解析

<eveapi version="2"> 
<currentTime>2012-11-12 10:36:35</currentTime> 
    <result> 
    <rowset name="entries" key="refID" columns="date,refID,refTypeID,ownerName1,ownerID1,ownerName2,ownerID2,argName1,argID1,amount,balance,reason"> 
    <row date="2012-11-12 10:46:49" refID="6570815512" refTypeID="10" ownerName1="Captain Vampire" ownerID1="159434479" ownerName2="The Condemned and Convicted" ownerID2="98032142" argName1="" argID1="0" amount="5000000.00" balance="13072537.98" reason="DESC: something "/> 
    <row date="2012-11-10 02:27:48" refID="6561124130" refTypeID="85" ownerName1="CONCORD" ownerID1="1000125" ownerName2="Justin Schereau" ownerID2="90541382" argName1="Unertek" argID1="30002413" amount="42300.00" balance="7972463.03" reason="10015:1,10019:1,11899:1,22822:1,"/> 
    <row date="2012-11-09 23:27:24" refID="6560673105" refTypeID="85" ownerName1="CONCORD" ownerID1="1000125" ownerName2="Blackcamper" ownerID2="754457655" argName1="Illamur" argID1="30002396" amount="25000.00" balance="7930163.03" reason="11898:1,"/> 
    </rowset> 
    </result> 
<cachedUntil>2012-11-12 11:03:35</cachedUntil> 
</eveapi> 

任何幫助,將不勝感激

感謝

+0

謝謝你的回答。我嘗試了穆罕默德的第一個,它的工作。這兩種解決方案之間有什麼優點和缺點? –

回答

3

您可以直接使用xpath如下

$xml = simplexml_load_file($eveAPI); 

/* Search for <a><b><c> */ 
$result = $xml->xpath('//result/rowset/row[@refTypeID=10]'); 

foreach($result as $value) { 
    echo $value['reason'] = trim(str_replace('DESC:','',$value['reason'])); 
    echo "Skill Number:".$value['refTypeID']." -- Skill Points: ".$value['ownerName1']." -- Level: ".$value['reason']."<br />"; 
} 
+0

+1不錯的解決方案 – ManseUK

+0

謝謝。這很有用。還允許我在最後輕鬆添加一些數學函數! –

+0

+使用評論 – Baba

0

嘗試

// Loop Through Skills 
foreach ($xml->result->rowset->row as $value) { 
if($value['refTypeID'] == 10){ 
echo "Skill Number:".$value['refTypeID']." -- Skill Points: ".$value['ownerName1']." -- Level: ".str_replace('DESC:', '', $value['reason'])."<br />"; 
} 
}; 
0

您可以使用continue跳過行你不需要:

foreach ($xml->result->rowset->row as $value) { 
    if ($value['refTypeID'] != "10") { 
     // skip 
     continue; 
    } 
    //etc ... 
} 

,並使用str_replace用於去除DESC:形式的字符串:

$reason = str_replace('DESC: ','',$value['reason']); 

注意:這也DESC:後刪除空間

+0

Downvoter ...爲什麼? – ManseUK