如何使用php动态更改xml节点的值

时间:2015-03-09 11:31:14

标签: php xml

<?xml version="1.0" encoding="UTF-8" ?>
    <SMS>
        <authentification>
            <username>xxxx</username>
            <password>xxxx</password>
        </authentification>
        <recipients>
            <number>8309042932</number>
        </recipients>
    </SMS>

我的号码节点有一个动态生成的号码供不同的人使用,我想加载所有号码,但我只得到最后一个号码。

用于创建xml字符串的代码:

<?xml version="1.0" encoding="UTF-8" ?> 
$xmlstring = 
"<SMS> 
     <authentification> 
        <username>xxxx</username> 
        <password>xxxx</password> 
     </authentification> 
     <recipients>"; 
foreach($gsmnumbers as $number) { 
   $number = explode(",", $number); 
   foreach($number as $num) { 
      $count = count($num); 
      for($i = 0; $i < $count; $i++) { 
         $xmlHalf = "<gsm>$num</gsm>"; 
      }
   }
} 
$xmlSecondHalf = "</recipients> </SMS>"; 

2 个答案:

答案 0 :(得分:0)

试试这个,代码中的各种错误。

基本上,如果使用.=语法,则可以连接到现有字符串的末尾,只需使用=将字符串替换为新值。

此外,<?xml version="1.0" encoding="UTF-8" ?>需要在字符串中将其标识为有效的XML字符串。

$xmlstring = '
<?xml version="1.0" encoding="UTF-8" ?> 
<SMS> 
     <authentification> 
        <username>xxxx</username> 
        <password>xxxx</password> 
     </authentification> 
     <recipients>'; 

foreach($gsmnumbers as $number) { 
   $nums = explode(",", $number); 
   foreach($nums as $num) { 
       $xmlstring .= "<gsm>$num</gsm>"; 
   }
} 
$xmlstring .= "</recipients></SMS>"; 

答案 1 :(得分:0)

不要将XML写为字符串,为此使用XML库。在创建XML时,库通常会阻止您自己动手。它还使您的代码更具可读性。例如:

// process and transform input data

$gsmnumbers = ['1234,5678,9012'];
$gsms = [];
foreach ($gsmnumbers as $number) {
    $nums = explode(",", $number);
    foreach ($nums as $num) {
        $gsms[] = $num;
    }
}

// create XML

$request = new SimpleXMLElement('<SMS/>');

$authentication = $request->addChild('authentification');
$authentication->username = 'XXXX';
$authentication->password = 'XXXX';

$recipients = $request->addChild('recipients');    
foreach ($gsms as $gsm) {
    $recipients->addChild('gsm', $gsm);
}

echo $request->asXML();

示例输出:

<?xml version="1.0"?>
<SMS><authentification><username>XXXX</username><password>XXXX</password></authentification><recipients><gsm>1234</gsm><gsm>5678</gsm><gsm>9012</gsm></recipients></SMS>