网站首页php
PHP操作xml实例
发布时间:2022-01-06 03:37:06编辑:阅读(593)
- 读入xml内容, 如:
$template = <<<EOF
<Header>
<EInvoiceTag></EInvoiceTag>
<EInvoiceID></EInvoiceID>
<Version></Version>
</Header>
<EInvoiceData>
<Main>
<EInvoiceName></EInvoiceName>
<EInvoiceCode></EInvoiceCode>
<EInvoiceNumber></EInvoiceNumber>
</Main>
</EInvoiceData>
EOF;
使用simplexml_load_string读入xml内容, 若最外层无根点节元素, 需手动添加
$template = '<xml>' . $template . '</xml>';
$templateObj = simplexml_load_string($template);
2. 如此, 就得到xml内容的对象了, 可直接赋值操作:
$templateObj->Header->EInvoiceTag = 'CZEI50';
$templateObj->Header->EInvoiceID = '1239612200-02106014';
$templateObj->Header->Version = '1.3.1';
$templateObj->EInvoiceData->Main->EInvoiceName = '1.1.2';
$templateObj->EInvoiceData->Main->EInvoiceCode = '31160120';
$templateObj->EInvoiceData->Main->EInvoiceNumber = '0002269321';
3. 再将对象转换成数组
function object2array($obj) {
$obj = (array)$obj;
foreach ($obj as $k => $v) {
if (gettype($v) == 'resource') {
return;
}
if (gettype($v) == 'object' || gettype($v) == 'array') {
$obj[$k] = (array)object2array($v);
}
}
return $obj;
}
$templateArr = object2array($templateObj);
4. 再将数组转换成xml
function array2xml($data, $root = true)
{
$str = "";
if ($root) {
$str .= "<xml>";
}
foreach ($data as $key => $val) {
if (is_array($val)) {
$child = array2xml($val, false);
$str .= "<$key>{$child}</$key>";
} else {
$str .= "<$key>{$val}</$key>";
}
}
if ($root) {
$str .= "</xml>";
}
return $str;
}
$xmlContent = array2xml($templateArr, false);
echo $xmlContent;
最终输出结果:
<Header>
<EInvoiceTag>CZEI50</EInvoiceTag>
<EInvoiceID>1239612200-02106014</EInvoiceID>
<Version>1.3.1</Version>
</Header>
<EInvoiceData>
<Main><EInvoiceName>1.1.2</EInvoiceName>
<EInvoiceCode>31160120</EInvoiceCode>
<EInvoiceNumber>0002269321</EInvoiceNumber>
</Main>
</EInvoiceData>
评论