0

XML値を変更して、XMLとして保存し直そうとしています。名前空間を持たない要素を変更すると、正常に機能します。問題は、変更したい値が名前空間にある場合です。見つけて印刷することはできますが、変更は無視されます。このような:

$ns = $xmlsingle->children('mynamespace');
foreach ($ns as $myelement)
{
    echo "my element is: [$myelement]";
    //I can change it:
    $myelement = "something else";
    echo "my element is now: [$myelement]"; //yay, value is changed!
}
//GREAT!
//But when I save the XML back, the value is not changed... apparently the children method creates a new object; not a link to the existing object
//So if I copy/paste the code above, I have the original value, not the changed value
$ns2 = $xmlsingle->children('mynamespace');
foreach ($ns2 as $myelement)
{
    echo "my element is UNCHANGED! [$myelement]";
}
//So my change's not done when I save the XML.
$xmlsingle->asXML(); //This XML is exacly the same as the original XML, without changes to the namespaced elements.

**コンパイルされない可能性のあるばかげたエラーは無視してください。元のコードからテキストを再入力しました。そうしないと、大きすぎます。コードは機能しますが、XMLに戻すと、NAMESPACED要素の値だけが変更されません。

私はPHPの専門家ではなく、他の方法で名前空間要素にアクセスする方法がわかりません...これらの値を変更するにはどうすればよいですか?私はどこでも検索しましたが、値を読み取る方法の説明しか見つかりませんでした。

4

1 に答える 1

1

次のようなものを試してください:

$xml = '
<example xmlns:foo="bar">
  <foo:a>Apple</foo:a>
  <foo:b>Banana</foo:b>
  <c>Cherry</c>
</example>';

$xmlsingle = new \SimpleXMLElement($xml);
echo "<pre>\n\n";
echo $xmlsingle->asXML();
echo "\n\n";

$ns = $xmlsingle->children('bar');
foreach ($ns as $i => $myelement){
    echo "my element is: [$myelement] ";

    //$myelement = "something else"; // <-- OLD
    $ns->$i = 'something else'; // <-- NEW

    echo "my element is now: [$myelement]"; //yay, value is changed!
    echo "\n";
}
echo "\n\n";
echo $xmlsingle->asXML();
echo "\n</pre>";

結果は次のようになります。

    
    
      アップル
      バナナ
      チェリー
    

    私の要素は:[Apple]私の要素は今:[何か他のもの]
    私の要素は:[バナナ]私の要素は今:[何か他のもの]

    
    
      他の何か
      他の何か
      チェリー
    

    

この助けを願っています。

于 2013-03-23T01:32:21.417 に答える