如何动态显示相应输入数组的xml标签?

时间:2016-01-30 00:22:32

标签: php html arrays xml

我的代码是这样的:http://pastebin.com/G74JY27f

<?php
$param = array('sex'=>'Mr.',
  'family_name'=>'Mourinho',
  'first_name'=>'Jose',
  'booking_phone'=>'123456',
  'booking_mobile'=>'123',
  'booking_email'=>'mourinho@gmail.com',
  'passenger_sex'=>array(
    'Sgl'=>array('Mr.'),
    'Dbl'=>array('Mr.','Mr.','Mr.','Mr.'),
  ),
  'passenger_family_name'=>array(
    'Sgl'=>array('Bale'),
    'Dbl'=>array('Hazard','Ronaldo','Messi','Beckham'),
  ),
  'passenger_first_name'=>array(
    'Sgl'=>array('Gareth'),
    'Dbl'=>array('Eden','Christiano','Lionel','David'),
  )
);

echo '<pre>';print_r($param);echo '</pre>';

$xml = "<?xml version='1.0' encoding='utf-8' ?>

  <Request>

    <BookingRequest>                            

      <Name>".$param['first_name']."</Name>

      <Email>".$param['booking_email']."</Email>

      <Phone>".$param['booking_phone']."</Phone>

      <MPhone>".$param['booking_mobile']."</MPhone>

      <Passenger Room='SGL'>

        <PassSex>Mr</PassSex>

        <PassLocalNm>Gareth</PassLocalNm>

        <PassFirstNm> Gareth </PassFirstNm>

        <PassLastNm> Bale</PassLastNm>

      </Passenger>  

    </BookingRequest>

  </Request>";

$json = json_encode($xml);
$response_array = json_decode($json,TRUE);
print_r($response_array);
die();
?>

print_r($param)的结果,它是一个数组

print_r($response_array)的结果,它是xml

xml中的名称标签,电子邮件标签,电话标签和mphone标签,根据数组中的数据

但问题是乘客标签,它仍然是静态的

似乎使用foreach,但我仍然感到困惑

结果将有五个乘客标签

所以我想要像http://pastebin.com/t380Aits

这样的输出

如何订购输出看起来像上面的链接?

1 个答案:

答案 0 :(得分:1)

您可以使用foreach循环将乘客标签添加到xml变量。

您可以通过循环遍历其中一个多维参数,然后遍历这些值并使用每个数组的键来获取其他数组中的相关数据。

有关如何执行此操作的示例,请参阅以下工作代码。

$xml = "<?xml version='1.0' encoding='utf-8' ?>

    <Request>

        <BookingRequest>                              

            <Name>".$param['first_name']."</Name> 

            <Email>".$param['booking_email']."</Email> 

            <Phone>".$param['booking_phone']."</Phone> 

            <MPhone>".$param['booking_mobile']."</MPhone>
";
// loop through one of the multi dimensional arrays
foreach ($param['passenger_sex'] as $type => $values)
{
    // loop through all values and add a Passenger record to $xml
    foreach ($values as $key => $val)
    {
        // use the $type array key, and the $key from the second loop to get the values
        $xml .= "
            <Passenger Room='".$type."'>

                <PassSex>".$param['passenger_sex'][$type][$key]."</PassSex>

                <PassLocalNm>".$param['passenger_first_name'][$type][$key]."</PassLocalNm>

                <PassFirstNm> ".$param['passenger_first_name'][$type][$key]." </PassFirstNm>

                <PassLastNm> ".$param['passenger_family_name'][$type][$key]."</PassLastNm>

            </Passenger>
";
    }
}
// add the closing tags to the xml string
$xml .= "
        </BookingRequest>

    </Request>";