[使用PHP替换xml / plist文件中的字符串

问题描述 投票:0回答:3

我在目录中有两个.plist文件,它们看起来都像这样:

<dict>
    <key>bundle-identifier</key>
    <string>TEXT</string>
    <key>bundle-version</key>
    <string>VESRION</string>
    <key>kind</key>
    <string>software</string>
    <key>subtitle</key>
    <string>TEXT</string>
    <key>title</key>
    <string>TEXT</string>
  </dict>

我能够通过以下方式获得title的值/字符串:

$files = array();
foreach (glob("../../plists/*.plist") as $file) {
    $files[] = $file;
    //echo "$file";

    $fileContent = file_get_contents($file);
    $xml = simplexml_load_string($fileContent) or die("Error: Cannot create object");
    $resultNames = $xml->dict->array->dict->dict->string[4] . '<br /> <br />';
    //echo $resultNames;

}

现在,我想用php更改每个字符串的[[title的值/字符串,就像我更改其中一个字符串的title的值/字符串一样,我不希望另一个受它影响,有可能吗?

php xml plist
3个回答
2
投票
[不确定标题的回声是如何工作的,但是在此代码中,我使用XPath查找具有内容<key>title元素。然后,它获取以下<string>元素的值。

要更新它,您在SimpleXML中使用了一些软糖以使其设置<string>元素的值,然后将结果XML保存回相同的文件名。...

$xml = simplexml_load_string($fileContent) or die("Error: Cannot create object"); // Find the correct string element from the preceding key for title $titleString = $xml->xpath('//key[.="title"]/following-sibling::string')[0]; // Set new value $titleString[0] = "new Title1"; // Save the file $xml->asXML($file);

如果您通过文件名标识内容,然后选中$file,但是如果您只能通过标题来标识它,那么您将需要检查它是否找到了您想要的标题。

$titleToUpdate = "Correct Title2"; $fileContent = file_get_contents($file); $xml = simplexml_load_string($fileContent) or die("Error: Cannot create object"); $titleString = $xml->xpath('//key[.="title"]/following-sibling::string[.="'.$titleToUpdate.'"]'); // Check there is 1 matching item if ( count($titleString) == 1 ) { $titleString[0][0] = "new Title12"; $xml->asXML($file); }


0
投票
我不确定是否了解所有内容,但是您可以使用DomDocument来更改值。

$doc = new DOMDocument; $doc->load('your_xml_file.xml'); $elements = $doc->getElementsByTagName("string"); foreach ($elements as $element) { //$element->nodeName will be "string" $nodes = $element->childNodes; foreach ($nodes as $node) { $node->nodeValue = 'New value'; } } $doc->save("newfile.xml")


0
投票
虽然不漂亮,但是可以。

$doc = new DOMDocument; $doc->load('file_address'); $elements = $doc->documentElement; $found = false; foreach ($elements->childNodes AS $item) { if($found){ $item->nodeValue = 'changed'; $found = false; }else{ if($item->nodeName == 'key' && $item->nodeValue == 'title'){ $found = true; } } } $doc->saveXML();

© www.soinside.com 2019 - 2024. All rights reserved.