سؤال

I hope someone can help as this is driving me insane.

I need to update an existing XML file using PHP. If the values in one of the nodes equals something, then I want to add a new child element with some text in it.

Here is an example of the XML file:

<properties>
  <property>
    <address>
      <street>Example Road</street>
      <locality>Fitzrovia</locality>
      <town>London</town>
      <postcode>NW1</postcode>
    </address>
  </property>
  <property>
    <address>
      <street>Default Street</street>
      <locality>Sample</locality>
      <town>London</town>
      <postcode>EC1</postcode>
    </address>
  </property>
</properties>

The PHP which I have at the moment:

$dom = new DOMDocument();
$dom->load('http://example.com/example.xml');
$xpath = new DOMXPath($dom);

$postcode = $xpath->query('property/address/postcode');
foreach($postcode as $region)
{
    $r = $region->nodeValue;
    if (preg_match('/^nw(?=[0-9]*)/i', $r)) {
        $region->nodeValue = 'North West London';
    }
    else if (preg_match('/^n(?=[0-9]*)/i', $r)) {
        $region->nodeValue = 'North London';
    }
    else if (preg_match('/^e(?=[0-9]*)/i', $r)) {
        $region->nodeValue = 'East London';
    }
    else if (preg_match('/^se(?=[0-9]*)/i', $r)) {
        $region->nodeValue = 'South East London';
    }
    else if (preg_match('/^sw(?=[0-9]*)/i', $r)) {
        $region->nodeValue = 'South West London';
    }
    else if (preg_match('/^w(?=[0-9]*)/i', $r)) {
        $region->nodeValue = 'West London';
    }
    else if (preg_match('/^ec(?=[0-9]*)/i', $r)) {
        $region->nodeValue = 'East Central London';
    }
    else if (preg_match('/^wc(?=[0-9]*)/i', $r)) {
        $region->nodeValue = 'West Central London';
    }
    else {
        $region->nodeValue = 'Outer London';
    }
}

$dom->save('export.xml');

What I am trying to do, is if the postcode equals a particular value, then a new child node will be added to the 'address' node with some text.

I have encountered some issues, where I could get a new child node to be generated, but it would add lots of them and all in only one part of the XML file, as opposed to one isntance within each 'property' node.

I hope this makes sense as I could really do with some assistance.

Thanks in advance :)

هل كانت مفيدة؟

المحلول

You should use DOMDocument::createElement to create a new node and DOMNode::appendChild to append the new node.

Example:

if (preg_match('/^nw(?=[0-9]*)/i', $r)) {
    $element = $dom->createElement('your_node_name', 'North West London');
    $region->parentNode->appendChild($element);
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top