【问题标题】:PHP open file and replace content [closed]PHP打开文件并替换内容[关闭]
【发布时间】:2012-08-13 05:32:55
【问题描述】:
<?php
$modcontent = file_get_contents('hello.xml');
preg_match("/<Content(.*?)>(.+?)<\/Content/s", $modcontent, $xmlmatches);
$search  = array('<![CDATA[',']]>');
$replace = array('','');
$thenewone = str_replace($search, $replace, $xmlmatches[2]);
fopen('hello.xml');
fwrite($thenewone);
fclose('hello.xml');
?>

嗨,从上面的代码开始(不起作用),你能不能让它修改 hello.xml 文件以只保留 之间的内容,就像在 preg_match 中一样? hello.xml 在这里http://www.google.com/ig/modules/hello.xml。 由于我的PHP和我的英语知识相当低,我会用不同的词再次解释,希望你能理解我的意思。我想要一个可以打开 hello.xml 文件、读取 Content 标签之间的内容、写入该内容并替换文件中其他所有内容并保存 hello.xml 文件的 PHP 脚本。因此,在所有这些操作之后,.xml 应该只包含 Hello, world!。 非常感谢!

【问题讨论】:

  • 这是一个可怕的替代品!很容易创建无效的 XML .. 而且,问题应该解释“不起作用”是什么意思 ..
  • 好吧,不起作用意味着我的代码没有对那个 hello.xml 文件做任何事情(也许你可以下载 hello.xml 文件并测试它,如果不是太麻烦的话)。另外,我不关心无效的 XML,因为在脚本对 XML 文件进行修改后,其内容将不再是 xml ;)
  • Daniel,我建议您最好阅读有关 SimpleXML 的内容。这会对你有很大帮助。了解 PHP 内置库总是比每次都重新发明那些简单(或不那么)的东西要好。
  • 感谢您的建议,但我认为SimpleXML只会显示一个XML文件,不会做我想做的事;我需要修改那个 xml 文件。此外,我现在开始学习 PHP 有点老了 - 只有上面的错误代码花了我半天时间。我真的没有时间,所以我在这里寻求帮助:(

标签: php regex fopen file-get-contents fwrite


【解决方案1】:

在这里尝试使用我的最爱DOMDocument

<?php 
$xml = file_get_contents('http://www.google.com/ig/modules/hello.xml');

$dom = new DOMDocument("1.0","UTF-8");
@$dom->loadXML($xml);
$dom->preserveWhiteSpace = false;
//Get the node by tag then get the textContent/nodeValue
$content = $dom->getElementsByTagName('Content')->item(0)->textContent;

//Hello, world! 
print_r($content);
//Write to file
file_put_contents('hello.txt',$content);
?>

【讨论】:

  • 我必须对这个线程做点什么吗?关闭,标记已解决等?我看不到任何选项。
  • 没关系,看来有些家伙还是关闭了它。再次感谢 m8!
猜你喜欢
  • 2018-08-05
  • 2015-10-01
  • 2017-04-13
  • 1970-01-01
  • 1970-01-01
  • 2021-03-01
  • 2011-04-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多