【问题标题】:How to replace a special xml tag by using php如何使用 php 替换特殊的 xml 标签
【发布时间】:2013-05-21 23:28:23
【问题描述】:

我有一个这样的 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

【问题讨论】:

    标签: php xml replace tags


    【解决方案1】:

    您可以使用 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");
    

    【讨论】:

      【解决方案2】:

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

      <?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...
                     }
           }
      }
      

      【讨论】:

      • 感谢您的回答,但是,此解决方案的负载很重,如果我的 xml 文件非常大,这种方式需要时间。您能建议一个更好的功能吗?tnx
      • @sepidehfaraji 我已经修改了我的脚本并添加了其他功能,但这与您的文件不完全匹配,但我希望对您有所帮助!
      猜你喜欢
      • 2018-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-14
      • 2017-12-12
      • 2012-09-01
      • 2014-05-04
      • 1970-01-01
      相关资源
      最近更新 更多