【发布时间】:2014-01-06 06:45:03
【问题描述】:
我正在上大学,不熟悉 PHP 正则表达式,但我对自己需要做什么有所了解。基本上,我需要创建一个 PHP 程序来读取包含多个“故事”的 XML 源代码,并将它们的详细信息存储在 mySQL 数据库中。我已经设法创建了一个选择每个故事的表达式,但我需要进一步分解这个表达式以便获得故事中的每个元素。这是 XML:
XML
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="test.xsl"?>
<latestIssue>
<issue number="256" />
<date>
<day> 21 </day>
<month> 1 </month>
<year> 2011 </year>
</date>
<story>
<title> Is the earth flat? </title>
<author> A. N. Redneck </author>
<url> http://www.HotStuff.ie/stories/story123456.xml </url>
</story>
<story>
<title> What the actress said to the bishop </title>
<author> Brated Film Critic </author>
<url> http://www.HotStuff.ie/stories/story123457.xml </url>
</story>
<story>
<title> What the year has in store </title>
<author> Stargazer </author>
<url> http://www.HotStuff.ie/stories/story123458.xml </url>
</story>
</latestIssue>
所以我需要从每个故事中获取标题、作者和网址,并将它们作为一行添加到我的数据库中。到目前为止,这是我所拥有的:
PHP
<?php
$url = fopen("http://address/to/test.xml", "r");
$contents = fread($url,10000000);
$exp = preg_match_all("/<title>(.+?)<\/url>/s", $contents, $matches);
foreach($matches[1] as $match) {
// NO IDEA WHAT TO DO FROM HERE
// $exp2 = "/<title>(.+?)<\/title><author>(.+?)<\/author><url>(.+?)<\/url>/";
// This is what I had but I'm not sure if it's right or what to do after
}
?>
非常感谢各位的帮助,我整天都被困在这个问题上,根本无法理解正则表达式。一旦我设法获得了每个故事的详细信息,我就可以轻松地更新数据库。
编辑: 感谢您的回复,但您确定这不能用正则表达式完成吗?问题只是说“使用正则表达式来分析 XML 并提取您需要的相关数据。请注意,有关每个故事的信息都分布在几行 XML 中”。也许他犯了一个错误,但我不明白如果不能这样做,他为什么会这样写。
【问题讨论】:
-
这里的正则表达式是wrong tool。您想使用 XML 解析器。
-
用正则表达式是可能的,但同样也可以用大锤固定螺丝。仅仅因为你 can 并不意味着它是正确的方法。我会说作业不正确,或者它试图让你比你需要的更努力。