Domanda

I am creating PHP system for edit XML files to translation of game.

I am using DOM e.g for file-comparision for translators (with update XML file).

I have old and new XML (in advance: I can not change XML structure) with new strings and/or new IDs.

For future echo node value to comparision by the same ID order, I have following code:

<?php
   $xml2 = new DOMDocument('1.0', 'utf-16');
   $xml2->formatOutput = true;
   $xml2->preserveWhiteSpace = false;
   $xml2->load(substr($file, 0, -4).'-pl.xml');

   $xml = new DOMDocument('1.0', 'utf-16');
   $xml->formatOutput = true;
   $xml->preserveWhiteSpace = false;
   $xml->load($file);

   for ($i = 0; $i < $xml->getElementsByTagName('string')->length; $i++) {

       if ($xml2->getElementsByTagName('string')->item($i)) {
          $element_pl = $xml2->getElementsByTagName('string')->item($i);
          $body_pl = $element_pl->getElementsByTagName('body')->item(0);
          $id_pl = $element_pl->getElementsByTagName('id')->item(0);
       } else $id_pl->nodeValue = "";

       $element = $xml->getElementsByTagName('string')->item($i);
       $id = $element->getElementsByTagName('id')->item(0);
       $body = $element->getElementsByTagName('body')->item(0);


       if ($id_pl->nodeValue == $id->nodeValue) {
          $element->appendChild( $xml->createElement('body-pl', $body_pl->nodeValue) );
       }

   }

   $xml = simplexml_import_dom($xml);
?>

Above code change:

<?xml version="1.0" encoding="utf-16"?>
<strings>
  <string>
    <id>1</id>
    <name>ABC</name>
    <body>English text</body>
  </string>
</strings>

to (by adding text from *-pl.xml file):

<?xml version="1.0" encoding="utf-16"?>
<strings>
  <string>
    <id>1</id>
    <name>ABC</name>
    <body>English text</body>
    <body-pl>Polish text</body-pl>
  </string>
</strings>

But I need find "body" value in *-pl.xml by "name" value.

"For" loop:
 get "ABC" from "name" tag [*.xml] ->
 find "ABC" in "name" tag [*-pl.xml] ->
 get body node from that "string" [*-pl.xml]

I can do that by strpos(), but my (the smallest) file have 25346 lines..

Is there something to do e.g. "has children ("name", "ABC") -> parent" ?

Then I can get "body" value of this string.

Thank you in advance for suggestions or link to similar, resolved ask,

Greetings

È stato utile?

Soluzione

You need XPath expressions:

//name[text()='ABC']/../body

or

//name[text()='ABC']/following-sibling::body

Check the PHP manual for DOMXPath class and its query method. In a nutshell, you'd use it like this:

$xpath = new DOMXPath($dom_document);

// find all `body` nodes that have a `name` sibling
// with an `ABC` value in the entire document
$nodes = $xpath->query("//name[text()='ABC']/../body");

foreach($nodes as $node) {
    echo $node->textContent , "\n\n";
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top