SimpleXML从XML文件中获取特定数据

时间:2014-04-18 15:00:08

标签: php xml simplexml jomsocial

我正在为JomSocial制作一个插件,它将根据XML文件显示登录用户的帐单信息。我在创建插件方面取得了很好的进展,我似乎无法正确创建php语句的语法,因此我可以在页面的各个位置填充数据。这是XML文件:

<Inquiry>
<Billing>
<Version>4.5.1</Version>
<startTime><![CDATA[4/15/2014 11:09 PM]]></startTime>
<endTime><![CDATA[4/15/2014 11:12 PM]]></endTime>
<Date>20140415</Date>
<MemberId ID="0ESING">
  <BillingInfo>
    <StatementEndDate>20140430</StatementEndDate>
    <BillingSubAccount>
    </BillingSubAccount>
    <BalanceForward>628.32</BalanceForward>
    <BalanceDue>372</BalanceDue>
    <Payments>-300</Payments>
</MemberId>
<MemberId ID="F00421">
</BillingInfo>
<BillingInfo>
<StatementEndDate>20140430</StatementEndDate>
 <BillingSubAccount>
 </BillingSubAccount>
 <BalanceForward>1158.36</BalanceForward>
 <BalanceDue>93.45</BalanceDue>
 <Payments>-1158.36</Payments>

到目前为止,这是PHP:

$user =& CFactory::getRequestUser();
$cuser = CFactory::getUser();  
$owner = CFactory::getUser($row->user->id); 
$ptype = $cuser->getProfileType();
$billingid = $owner->getInfo('FIELD_BILLINGID');
$lastname = $owner->getInfo('FIELD_FAMILYNAME');
$uname = $cuser->username;
$memid = $cuser->id;
$name = $cuser->getDisplayName();
$isMine = COwnerHelper::isMine($cuser->id, $user->id);
$config = CFactory::getConfig();

$source = file_get_contents('data/201404.xml');
$xml = new SimpleXMLElement($source);
$balance = $xml->Billing->MemberId->BillingInfo->BalanceDue;
$BalanceForward = $xml->Billing->MemberId->BillingInfo->BalanceForward;
$Payments = $xml->Billing->MemberId->BillingInfo->Payments;
ob_start();

if( $isMine ) {
    if($ptype == '2') { 

    if(strcasecmp($uname, $billingid) == 0) {

然后,在页面中调用字段:

<?php echo "<div>Balance Due: $". $balance ." | Balance Forward: $" . $BalanceForward . " | Payment: $" . $Payments . "</div>"; ?>

这会引入XML文件的第一条记录。几个小时我一直在尝试这样的事情:

$source = file_get_contents('data/201404.xml');
$xml = new SimpleXMLElement($source);
$balance = $xml->Billing->MemberId[.$uname.]->BillingInfo->BalanceDue;
$BalanceForward = $xml->Billing->MemberId[.$uname.]->BillingInfo->BalanceForward;
$Payments = $xml->Billing->MemberId[.$uname.]->BillingInfo->Payments;

无济于事。我想拉动&#39;来自XML的子节点,其中MemberId ID =&#34; yadayada&#34;等于$ uname。我希望我很清楚,这是我在Stackoverflow上的第一篇文章!

2 个答案:

答案 0 :(得分:0)

为什么不使用simplexml_load_file()?它可以省去手动加载文件并将其放在simplexml_element中的麻烦。此外,我认为你的问题是因为XML文件本身无效,它需要1个根元素,但似乎包含零(或多个,取决于人们如何读取文件)。

答案 1 :(得分:0)

使用方括号表示法按名称访问属性,因此您要求member[0ESING]不正确,因为该属性名为ID

您可以迭代成员以查找匹配项:

foreach($xml->Billing->MemberId as $member){
    if($member['ID'] == $uname){
        $balance = $member->BillingInfo->BalanceDue;
        $BalanceForward = $member->BillingInfo->BalanceForward;
        $Payments = $member->BillingInfo->Payments;
    }
}