[英]Parsing a single XML section using a query string with PHP
我正在嘗試使用PHP從XML文件檢索單個部分。 這是我正在使用的代碼:
<?php
$articles = simplexml_load_file('articles.xml');
foreach ($articles as $articlecontent)
{
$title = $articlecontent->title;
$content = $articlecontent->content;
$author = $articlecontent->author;
$date = $articlecontent['date'];
echo "<h1>",$title,"</h1>\n",
"<p><i>",$date,"</i></p>\n",
"<p>",$content,"</p>\n",
"<p>",$author,"</p>\n",
"<p><time>",$date,"</time></p>\n"
;
}
?>
哪個顯示了XML文件中的所有部分,但是如何只解析一個結果卻使用查詢字符串來解析呢?
示例: articles.php?title=section-one
將檢索標題為“ section-one”的XML部分。
通過從PHP的超全局$_GET
數組中獲取標題,可以從查詢字符串中獲取標題,如下所示:
$title = false;
if (isset($_GET['title']))
{
$title = $_GET['title'];
}
然后最簡單的方法是將其與foreach
循環中XML文件的標題進行比較。
從URL中獲取標題的方法是使用$ _GET數組,然后按標題獲取所需的文章,我認為您可以使用不需要foreach循環的xpath
$title = $_GET['title'];
// there should go some sanitizing
$articles = simplexml_load_file('articles.xml');
//search for article by title
//assuming that xml root tag is articles and article tag is article and searching by attribute named title
$foundArticles = $articles->xpath('articles/article[@title='.$title.']');
//query depends on xml structure
// now you have array of matched articles with matching title from url
foreach($foundArticles as $singleArticle)
{
//do printing here
}
該代碼未經測試,但是原理應該起作用。
要從URL接收查詢字符串變量(在我們的示例中為“標題”),您也可以使用$_REQUEST
。 一點點糾正的代碼(@ user1597483)帶有一些更高級的更新。
$articles = simplexml_load_file('articles.xml');
$title = "";
if(isset($_REQUEST['title'])) //receiving Query String from URL
$title = $_REQUEST['title'];
if(count($articles)):
//Fixed search means that will one return article if 'section-one' in title
//$result = $articles->xpath("//article[title='Section-one']");
//Match All Search means that will return all articles that contains 'section-one' in title
$result = $articles->xpath("//article[contains(translate(title, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'),'".strtolower($title)."')]");
foreach ($result as $articleItem):
$title=$articleItem->title;
$content=$articleItem->content;
$author=$articleItem->author;
$date=$articleItem->date;
echo "<h1>",$title,"</h1>\n";
echo "<p><i>",$date,"</i></p>\n";
echo "<p>",$content,"</p>\n";
echo "<p>",$author,"</p>\n";
echo "<p><time>",$date,"</time></p>\n";
endforeach;
endif;
在上面的代碼中,我指定了兩種類型的過濾器,通過這些過濾器,您可以通過完全匹配獲得特定文章的結果,也可以通過contains
函數來獲得通配符類型的結果。 而且我還使用了translate
功能,它將title
元素的值轉換為小寫,還將查詢字符串變量的值轉換為小寫。 這樣,無論大小寫如何,條件都將以小寫形式檢查,如果條件匹配,則將返回結果文章。
如果標題過濾器正在運行且不匹配,則可以通過在foreach
循環測試中插入條件來實現。 如果是這樣,請使用continue
關鍵字跳過該條目:
$titleFilter = trim(isset($_GET['title']) ? $_GET['title'] : '');
...
foreach ($articles as $articlecontent)
{
$title = $articlecontent->title;
if (strlen($titleFilter) and $title !== $titleFilter) {
continue;
}
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.