0

我有$xmlstring带值的 xml 字段;

'<result>
  <customerAccount xmlns="http://www.ibm.com>
    <AccountStatus xmlns="">Due</AccountStatus>

    <ComponentCustomerAccount xmlns="">
      <Name>ADSL</Name>
      <CharacteristicValue>
        <Characteristic>
          <Name>Balance</Name>
        </Characteristic>
        <Value>0.0</Value>
      </CharacteristicValue>
      <CharacteristicValue>
        <Characteristic>
          <Name>Date</Name>
        </Characteristic>
        <Value>21.10.1990</Value>
      </CharacteristicValue>
      <AccountStatus>Active</AccountStatus>
    </ComponentCustomerAccount>

    <ComponentCustomerAccount xmlns="">
      <Name>IPTV</Name>
      <CharacteristicValue>
        <Characteristic>
          <Name>Balance</Name>
        </Characteristic>
        <Value>100</Value>
      </CharacteristicValue>
      <CharacteristicValue>
        <Characteristic>
          <Name>Date</Name>
        </Characteristic>
        <Value>21.10.1990</Value>
      </CharacteristicValue>
      <AccountStatus>Active</AccountStatus>
    </ComponentCustomerAccount>


  </customerAccount>
</result>';

我想在表格内的 HTML 字段中显示:

NAME       STATUS     VALUE

ADSL       ACTIVE     0.0
IPTV       ACTIVE     100

如您所见,我有一些重复的元素。ComponentCustomerAccount 重复,我可以有多个元素。我不需要第一个 AccountStatus 元素,但我需要 ComponentCustomerAccount 中的 AccountStatus 元素。我还需要 ComponentCustomerAccount 元素中的第一个元素名称。

    $xml = new SimpleXMLElement($xmlString);

    $html = "<table>";
    $html .= "<tr><th>Account Name</th><th>Status</th><th>Amount</th></tr>";
    foreach($xml->customerAccount as $cust) {

     $html .= "<tr><th>" . $cust->Name .
 "</th><th>" . $cust->AccountStatus. "</th><th>" . $cust->Value . "</th></tr>";


    }

    $html .= "</table>";

但我得到空白输出。我必须改变什么?谢谢

4

1 回答 1

2

您的 XML 在<customerAccount xmlns="http://www.ibm.com>. 一旦你解决了这个问题,你需要在循环内部进行迭代ComponentCustomerAccount

foreach($xml->customerAccount as $ca) {
    foreach ($ca->ComponentCustomerAccount as $cust) {
        $html .= "<tr><th>" . $cust->Name
        . "</th><th>" . $cust->AccountStatus. "</th><th>"
        . $cust->CharacteristicValue->Value . "</th></tr>";
    }
}
于 2013-03-18T13:35:34.407 回答