0

i have an existing XML file and i would like to change certain fields in it using PhP. For example say i want to change id and pw. Any help on how to open and write on the certain fields?

        <info>
            <contact:info xmlns:contact="urn:ietf:params:xml:ns:contact-1.0" xsi:schemaLocation="urn:ietf:params:xml:ns:contact-1.0
contact-1.0.xsd">
                <contact:id>reg_contact001</contact:id>
                <contact:authInfo>
                    <contact:pw>my-password</contact:pw>
                </contact:authInfo>
            </contact:info>
        </info> 
3
  • open it with note pad or ward pard or dreamwever change the pariticular place Commented Aug 26, 2013 at 7:35
  • use simplexml or a regex replace Commented Aug 26, 2013 at 7:37
  • I need to create a script in php in order to send different data each time. I found this us3.php.net/manual/en/function.xmlwriter-write-attribute.php although. Commented Aug 26, 2013 at 7:38

1 Answer 1

1
$xml = <<<XML
    <info>
        <contact:info xmlns:contact="urn:ietf:params:xml:ns:contact-1.0" xsi:schemaLocation="urn:ietf:params:xml:ns:contact-1.0 contact-1.0.xsd">
            <contact:id>reg_contact001</contact:id>
            <contact:authInfo>
                <contact:pw>my-password</contact:pw>
            </contact:authInfo>
        </contact:info>
    </info>
XML;

function changeXML ($xml, $params) {
    // prepare xml object
    $xmlObj = new SimpleXMLElement($xml);
    $namespaces = $xmlObj->getNameSpaces(true);
    $entry = $xmlObj->children($namespaces['contact']);

    // change data
    $entry->info->id = $params->id;
    $entry->info->authInfo->pw = $params->pw;

    return '<info>' . $entry->saveXML() . '</info>';
}

print_r($xml);

$params = new \stdClass();
$params->id = 1;
$params->pw = 'supercowpowers';

$result = changeXML($xml, $params);

print_r($result);

Output

<info>
    <contact:info xmlns:contact="urn:ietf:params:xml:ns:contact-1.0" xsi:schemaLocation="urn:ietf:params:xml:ns:contact-1.0 contact-1.0.xsd">
        <contact:id>reg_contact001</contact:id>
        <contact:authInfo>
            <contact:pw>my-password</contact:pw>
        </contact:authInfo>
    </contact:info>
</info>

<info>
    <contact:info xmlns:contact="urn:ietf:params:xml:ns:contact-1.0" schemaLocation="urn:ietf:params:xml:ns:contact-1.0 contact-1.0.xsd">
        <contact:id>1</contact:id>
        <contact:authInfo>
            <contact:pw>supercowpowers</contact:pw>
        </contact:authInfo>
    </contact:info>
</info>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.