替换用simplexml_load_file()加载的xml中的文本


Replace text in xml loaded with simplexml_load_file()?

我有这个xml文件:

<flats>
    <flat>
        <images1>http://www.example.com/image1.jpg</images1>
        <images2>http://www.example.com/image1.jpg</images2>
    </flat>
</flats>

我需要使用php加载它,然后替换一些节点名称来获得它(只需将image1images2更改为images

<flats>
    <flat>
        <images>http://www.example.com/image1.jpg</images>
        <images>http://www.example.com/image1.jpg</images>
    </flat>
</flats>

我设法加载并保存了文件,但我不知道如何替换节点名称。

$xml_external_path = 'http://external-site.com/original.xml';
$xml = simplexml_load_file($xml_external_path);
$xml->asXml('updated.xml');

更新:PHP

    $xml_external_path = 'http://external-site.com/original.xml';
    $xml = simplexml_load_file($xml_external_path);
    print_r($xml);
    $newXml = str_replace( 'images1', 'image',$xml ) ;
    print_r($newXml);

如果您只想重命名<images1><images2>标签,我建议您使用最简单的解决方案,即使用str_replace替换文本。

$xml_external_path = 'http://external-site.com/original.xml';
$xml = simplexml_load_file($xml_external_path);
$searches = ['<images1>', '<images2>', '</images1>', '</images2>'];
$replacements = ['<images>', '<images>', '</images>', '</images>'];
$newXml = simplexml_load_string( str_replace( $searches, $replacements, $xml->asXml() ) );
$newXml->asXml('updated.xml');

但是,如果您需要一种更复杂的方法来处理任务,您可能需要查看DOMDocument类,并构建自己的新XML

解析原始xml并创建一个新的xml:

$oldxml = simplexml_load_file("/path/to/file.xml");
// create a new XML trunk
$newxml = simplexml_load_string("<flats><flat/></flats>");
// iterate over child-nodes of <flat>
// check their name 
// if name contains "images", add a new child in $newxml
foreach ($oldxml->flat->children() as $key => $value) 
    if (substr($key, 0, 6) == "images") 
        $newxml->flat->addChild("images", $value);
// display new XML:
echo $newxml->asXML();

看到它工作:https://eval.in/301221

编辑:如果<flat>的所有子级都是<imageX>,则无需检查$key:

foreach ($oldxml->flat->children() as $value) 
    $newxml->flat->addChild("images", $value); 

编辑:以下是要使用xpath:更改的节点的简短而甜蜜的选择

foreach ($oldxml->xpath("/flats/flat/*[starts-with(local-name(), 'images')]") as $value)
    $newxml->flat->addChild("images", $value);

上面的xpath语句将选择以"images"开头的<flat>的所有子级,并将它们放入一个数组中。

看到它工作:https://eval.in/301233