0

タグのコンテンツ (属性ではなくコンテンツのみ) を変更する方法を知る必要があります。この親タグ内に内部タグは必要ありません。その中にテキストを入れるだけです。(次の xml ファイルの "1. Hello World" を置き換えます):

<config name="THIS" type="string">1. Hello World)</config>
<config name="IS" type="string">2. Hello World!</config>
<config name="SPARTA" type="string">3. Hello World?</config>

// create simple xml object
$xml = new SimpleXMLElement(file_get_contents('file.xml'));

// new names and values
$names  = array('THIS', 'SPARTA');
$values = array('1. Good bye world(', '3. Good bye world?');

// replace here
foreach($xml as $a => $xmlElement) {
     $indexOfName = array_search($names, (string)$xmlElement['name']);
     if ($indexOfName !== false) {
          // here I need to replace the value (e.g. 1. Hello World)) of config
          // with the attribute @name == $names[$i] with the new value
          // $values[$i] (3. Good bye world?)
     }
}
4

2 に答える 2

1

一時的な解決策を見つけました。新しい単純なxmlを作成し、現在の単純なxmlからすべてのものをコピーして、コンテンツ値を置き換えます

$newXml = new SimpleXMLElement('<' . $xml->getName() . '></' . $xml->getName() . '>');
foreach($xml as $a => $xmlElement) {
    $attr = $newXml->addChild($a, 'New content of the tag');
    foreach($xmlElement->attributes() as $k => $v) {
        $attr->addAttribute($k, $v);
    }
}
echo $newXml->asXML();

ただし、一時的です。誰かがより良い解決策を生み出すことができれば幸いです

于 2012-04-15T13:07:14.300 に答える
1

通常、親要素が必要です。親の構造がわかっている場合は、xpath を試すことができます。それ以外に、次のハックを試してみてください。

$xmlElement->{0} = $values[$indexOfName];
于 2012-04-15T10:42:07.327 に答える