使用PHP的SimpleXML将节点添加到带命名空间的XML

时间:2010-02-08 14:05:21

标签: php xml simplexml

<?xml version="1.0" encoding="ISO-8859-2"?>
    <!DOCTYPE pasaz:Envelope SYSTEM "loadOffers.dtd">
    <pasaz:Envelope xmlns:pasaz="http://schemas.xmlsoap.org/soap/envelope/">
        <pasaz:Body>
            <loadOffers xmlns="urn:ExportB2B">
                <offers />
            </loadOffers>
        </pasaz:Body>
    </pasaz:Envelope>

我要将一些子节点添加到“offer”节点,我正在使用SimpleXML。

PHP代码:$offer = $xml->offers->addChild('offer')返回错误。

这都错了,因为我在SimpleXML中处理名称空间时遇到了问题!请帮忙!

1 个答案:

答案 0 :(得分:2)

E.g。通过使用xpath获取目标/父元素。

<?php
$envelope = new SimpleXMLElement('<?xml version="1.0" encoding="ISO-8859-2"?>
<!DOCTYPE pasaz:Envelope SYSTEM "loadOffers.dtd">
<pasaz:Envelope xmlns:pasaz="http://schemas.xmlsoap.org/soap/envelope/">
  <pasaz:Body>
    <loadOffers xmlns="urn:ExportB2B">
      <offers />
    </loadOffers>
  </pasaz:Body>
</pasaz:Envelope>');

$envelope->registerXPathNamespace('pasaz', 'http://schemas.xmlsoap.org/soap/envelope/');
$envelope->registerXPathNamespace('b2b', 'urn:ExportB2B');
$ns = $envelope->xpath('//pasaz:Body/b2b:loadOffers/b2b:offers');
if ( 0<count($ns) ) {
  $offers = $ns[0];
  $offers->a = 'abc';
  $offers->x = 'xyz';
}
echo $envelope->asXml();

打印

<?xml version="1.0" encoding="ISO-8859-2"?>
<!DOCTYPE pasaz:Envelope SYSTEM "loadOffers.dtd">
<pasaz:Envelope xmlns:pasaz="http://schemas.xmlsoap.org/soap/envelope/">
  <pasaz:Body>
    <loadOffers xmlns="urn:ExportB2B">
      <offers><a>abc</a><x>xyz</x></offers>
    </loadOffers>
  </pasaz:Body>
</pasaz:Envelope>