我不得不把我的问题改成简单的问题
例如:我的XML文件名是:ABC.xml
在这个XML文件里面是:
<li class="thumb"><a class="Alibaba" href="google.com"></a></li>
所以,我的问题是:如何使用PHP在ABC.xml中搜索字符串,找到Alibaba name并替换为AlibabaColor name并保存到ABC.xml
请指导我,给我一个例子。谢谢你
您可以在许多其他函数中使用php str_replace来完成此操作。下面是几个例子->
如果XML已经在字符串中,你可以这样做
PHP:<?php
$myXmlString = str_replace('Alibaba', 'AlibabaColor', $myXmlString);
?>
如果您需要从另一个文件中获取XML数据,有几种方法可以做到这一点,这取决于您是否需要保存它,只是替换它并显示它,或者您正在做什么。其中一些可以归结为偏好。
只需要显示吗?
<?php
$xml = file_get_contents(/path/to/file); // or http://path.to/file.xml
$myXmlString = str_replace('Alibaba', 'AlibabaColor', $xml);
?>
需要更改文件本身吗?
<?php
$xml = file_get_contents(/path/to/file); // or http://path.to/file.xml
$myXmlString = str_replace('Alibaba', 'AlibabaColor', $xml);
file_put_contents(/path/to/file, $myXmlString);
?>
,
为了回答下面的评论,下面是我的服务器上的工作代码-> xml:<li>hello</li>
php: $file = '/home/username/public_html/xml.xml';
$xml = file_get_contents($file);
$text = str_replace('hello','world',$xml);
file_put_contents($file, $text);
xml.xml后:
<li>world</li>
请记住将'username'更改为正确的名称,或者使用FQDN,如果您觉得这样做更舒服的话。请确保该文件也具有由脚本写入的权限。