在PHP中修改XML

时间:2018-05-27 11:13:19

标签: php xml

我有下面的xml

<?xml version="1.0" encoding="UTF-8"?>
<!--Sample XML file generated by XMLSpy v2013 (http://www.altova.com)-->
<ftc:FATCA_OECD xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ftc="urn:oecd:ties:fatca:v2" xmlns:sfa="urn:oecd:ties:stffatcatypes:v2" version="2.0" xsi:schemaLocation="urn:oecd:ties:fatca:v2 FatcaXML_v2.0.xsd">
    <ftc:MessageSpec>
        <sfa:SendingCompanyIN>S519K4.99999.SL.392</sfa:SendingCompanyIN>
        <sfa:TransmittingCountry>JP</sfa:TransmittingCountry>
        <sfa:ReceivingCountry>US</sfa:ReceivingCountry>
        <sfa:MessageType>FATCA</sfa:MessageType>
        <sfa:MessageRefId>DBA6455E-8454-47D9-914B-FEE48E4EF3AA</sfa:MessageRefId>
        <sfa:ReportingPeriod>2016-12-31</sfa:ReportingPeriod>
        <sfa:Timestamp>2017-01-17T09:30:47Z</sfa:Timestamp>
    <ftc:SendingCompanyIN>testing</ftc:SendingCompanyIN></ftc:MessageSpec>
    <ftc:FATCA>
        <ftc:ReportingFI>
            <sfa:ResCountryCode>JP</sfa:ResCountryCode>
            <sfa:TIN>S519K4.99999.SL.392</sfa:TIN>
            <sfa:Name>Bank of NN</sfa:Name>
            <sfa:Address>
                <sfa:CountryCode>JP</sfa:CountryCode>
                <sfa:AddressFree>123 Main Street</sfa:AddressFree>
            </sfa:Address>
            <ftc:DocSpec>
                <ftc:DocTypeIndic>FATCA1</ftc:DocTypeIndic>
                <ftc:DocRefId>S519K4.99999.SL.392.50B80D2D-79DA-4AFD-8148-F06480FFDEB5</ftc:DocRefId>
            </ftc:DocSpec>
        </ftc:ReportingFI>
        <ftc:ReportingGroup>
            <ftc:NilReport>
                <ftc:DocSpec>
                    <ftc:DocTypeIndic>FATCA1</ftc:DocTypeIndic>
                    <ftc:DocRefId>S519K4.99999.SL.392.CE54CA78-7C31-4EC2-B73C-E387C314F426</ftc:DocRefId>
                </ftc:DocSpec>
                <ftc:NoAccountToReport>yes</ftc:NoAccountToReport>
            </ftc:NilReport>
        </ftc:ReportingGroup>
    </ftc:FATCA>
</ftc:FATCA_OECD>

我想更改节点值sfa:TIN并将xml保存在新文件中。如何在PHP中实现这一目标?我得到了示例但没有使用名称空间。

2 个答案:

答案 0 :(得分:1)

你可以这样做的一种方法是使用DOMDocumentDOMXPath并使用例如xpath表达式找到你的元素,它将在sfa命名空间中找到'TIN'元素。

/ftc:FATCA_OECD/ftc:FATCA/ftc:ReportingFI/sfa:TIN

要更新第一个找到的元素的值,您可以从query返回的DOMNodeList中获取第一个项目。

$doc = new DOMDocument();
$doc->loadXML($data);
$xpath = new DOMXPath($doc);
$res = $xpath->query("/ftc:FATCA_OECD/ftc:FATCA/ftc:ReportingFI/sfa:TIN");
if ($res->length > 0) {
    $res[0]->nodeValue = "test";
}
$doc->save("yourfilename.xml");

Demo

答案 1 :(得分:1)

您可以使用DOMDocument::getElementsByTagNameNS

使用以下解决方案
<?php
$dom = new DOMDocument();
$dom->load('old-file.xml');

//get all TIN nodes.
$nodesTIN = $dom->getElementsByTagNameNS('urn:oecd:ties:stffatcatypes:v2', 'TIN');

//check for existing TIN node.   
if (count($nodesTIN) === 1) {

    //update the first TIN node.
    $nodesTIN->item(0)->nodeValue = 'NEWVALUE_OF_TIN';
}

//save the file to a new one.
$dom->save('new-file.xml');