【问题标题】:Comma-Separated variable in foreach loop to xml rows in php scriptforeach 循环中的逗号分隔变量到 php 脚本中的 xml 行
【发布时间】:2020-11-05 10:29:01
【问题描述】:

我正在尝试创建一个循环,该循环将在 php 脚本中输出 xml 行。这些值来自逗号分隔的变量,如下所示:

$commaValues = '5773270,5778216';
$lubuvnaCommas = explode(',', $commaValues);

foreach($lubuvnaCommas as $row){
        $expected = $row;
        $destinations = "<cl_id>".$expected."</cl_id>";
    }

目标变量应在我的脚本中定义的 xml 结构中输出,如下所示:

$xml ='
   <?xml version="1.0" encoding="UTF-8"?>
   <destinations>
   '.$destinations.'
   </destinations>;

这意味着 xml 数据的最终输出应如下所示:

$xml ='
   <?xml version="1.0" encoding="UTF-8"?>
   <destinations>
   <cl_id>5773270</cl_id>
   <cl_id>5778216</cl_id>
   </destinations>';

我尝试了很多选项,我觉得我的循环中缺少一些不输出 xml 数据循环的东西。

【问题讨论】:

    标签: php arrays xml string foreach


    【解决方案1】:

    工作正常:

    $commaValues = '5773270,5778216';
    $lubuvnaCommas = explode(',', $commaValues);
    $destinations = '';
    
    foreach($lubuvnaCommas as $row){
        // Concatenate current value with previous ones
        $destinations .= "<cl_id>".$row."</cl_id>";
    }
    
    $xml ='
       <?xml version="1.0" encoding="UTF-8"?>
       <destinations>
       '.$destinations.'
       </destinations>';
    

    小提琴here.

    【讨论】:

    • 我在这个问题上被困了好几个小时。现在你解决了,感激不尽。谢谢亲爱的
    • 我知道 OP 接受了这个答案,但你能请echo $xml 并发布输出吗?出于某种原因,我没有得到问题中的预期输出。
    • 添加了一个小提琴。
    猜你喜欢
    • 2020-07-10
    • 2016-12-04
    • 2015-02-26
    • 2019-04-20
    • 2020-02-05
    • 1970-01-01
    • 2016-04-24
    • 2021-06-23
    • 2013-02-20
    相关资源
    最近更新 更多