如何使用 PHP 动态更改 XML 节点的值


how to dynamically change the value of an xml node with php

<?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>"; 

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

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

此外,<?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>"; 

不要将 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>