【问题标题】:How to parse php variable into xml tag..?如何将php变量解析为xml标签..?
【发布时间】:2018-05-04 09:50:25
【问题描述】:
<Address FormattedInd="true">
      <CityName>Athens Center</CityName>
           <County>'.$Country.'</County>
      <CountryName Code="GR" />  
</Address>

对于县,我可以使用 &lt;County&gt;'.$Country.'&lt;/County&gt;$Country="CountryName" 但是对于像 CountryName Code="GR" 这样的单个标签,我如何将代码“GR”作为 PHP 变量传递。 在这里,&lt;CountryName Code="GR" /&gt; 我需要从变量传递“GR”,比如$Code = "GR";

TIA

【问题讨论】:

    标签: php xml tags


    【解决方案1】:

    你可以在函数中做到这一点;

    function GenerateXML($tagname, $value)
    {
        return "
            <{$tagname}>
                {$value}
            </{$tagname}>
        ";    
    }
    

    或者,在 PHP 文件中

    <?
    print "<tagname>{$value}</tagname>";
    ?>
    

    任何一种方式都有效

    自闭标签;

    function XMLSelfClose($tagname, $valuename, $value)
    {
        return "<{$tagname} {$valuename}='{$value}' />";
    }
    
    print "<{$tagname} {$valuename}='{$value}' />";
    

    【讨论】:

    • 如何在自关闭 xml 标记中实现?在这里, 我需要从变量中传递“GR”。
    • 编辑了问题..请查看
    • 在哪里调用函数 XMLSelfClose($tagname, $valuename, $value) 这个函数..?
    【解决方案2】:

    使用 SimpleXML 比使用字符串创建 XML 更好,如果您开始按原样构建数据,则很容易弄乱内容。

    您的上述内容可以使用...创建。

    $Country = "Greece";
    $Code = "GR";
    
    // Create base document
    $xml =new SimpleXMLElement('<Address FormattedInd="true"></Address>');
    // Add in the CityName elment
    $xml->addChild("CityName", "Athens Center");
    $xml->addChild("Country", $Country);
    $countryName = $xml->addChild("CountryName");
    // With the CountryName element just created, add the Code attribute
    $countryName->addAttribute("Code", $Code);
    
    echo $xml->asXML();
    

    哪些输出...

    <?xml version="1.0"?>
    <Address FormattedInd="true"><CityName>Athens Center</CityName><Country>Greece</Country><CountryName Code="GR"/></Address>
    

    【讨论】:

      猜你喜欢
      • 2012-05-22
      • 1970-01-01
      • 1970-01-01
      • 2021-03-15
      • 2014-05-01
      • 2018-06-09
      • 2013-07-12
      • 2012-04-10
      • 1970-01-01
      相关资源
      最近更新 更多