0

我有一个这样的 xml 文件:

<?xml version="1.0"?>
<datas>
<books> 
<book>
<id>1</id>
<title>PHP Undercover</title>     
<author>Wiwit Siswoutomo</author>
</book>`enter code here`
<book>
<id>2</id>
<title>PHP Enterprise</title>     
<author>Wiwit Siswoutomo</author>
</book>
</books>
</datas>

现在我想用这种方式替换一个特殊的标签:在 xml 文件中搜索,如果它有一个 PHP Enterprise,找到它并用“新标题”替换它。我应该怎么办?TNX

4

2 回答 2

0

这个脚本会帮助你!!尝试这个 :)

<?php
function replace_Special_Str($mystring)
{
    //Load file
    $filename="./myfile.xml";
    if (!file_exists($filename)) { echo "There is not a myfile.xml file in the directory."; exit;}
    $xml = simplexml_load_file($filename);

    //search and replace particular node by book title
    $node = $xml->xpath('/datas/books[title="' . $mystring. '"]');
    if(sizeof($node) > 0) 
    {                                                                              
        $node[0]->title = 'My Title';
    }
    $xml->asXML('./aucstatus.xml');
}
?>

或者试试这个,

<users>
     <name>John</name>
     <address>My Address</address>
     <zipcode>12345</zipcode>
     <city>My City</city>
     <phone>555 1234-4321</phone>
</users>

PHP文件

fopen('users.xml');
while ($users->read()) {
     switch ($users->nodeType) {
          case (XMLReader::ELEMENT):
               if ($users->localName == "users") {
             $node = $reader->expand();
             $dom = new DomDocument();
             $n = $dom->importNode($node,true);
             $dom->appendChild($n);
             $simple_xml = simplexml_import_dom($n);
             $id = $simple_xml['id'];
             $name = $simple_xml->name;
             $address = $simple_xml->address;
                     // Custom code insert, update, whatever...
               }
     }
}
于 2013-05-27T06:46:35.560 回答
0

您可以使用 SimpleXML 解析文档:

$datas = new SimpleXMLElement("my.xml");
foreach ($datas->books->book as $book) {
    if (preg_match('/PHP Enterprise/', $book->title) {
       $book->title = "new title";
    }
}

$datas->asXML("my.xml");
于 2013-05-27T06:52:22.147 回答