2012-11-12 58 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