簡體   English   中英

如何將 php 變量解析為 xml 標簽..?

[英]How to parse php variable into xml tag..?

<Address FormattedInd="true">
      <CityName>Athens Center</CityName>
           <County>'.$Country.'</County>
      <CountryName Code="GR" />  
</Address>

對於縣,我可以使用<County>'.$Country.'</County> 其中$Country="CountryName"但是對於像 CountryName Code="GR" 這樣的單個標記,我如何將代碼“GR”作為 PHP 變量傳遞。 在這里, <CountryName Code="GR" />我需要從變量傳遞“GR”,比如$Code = "GR";

TIA

你可以在一個函數中做到這一點;

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}' />";

使用 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM