I have a list, consisting of links looking like this:
<a href=index.php?p=page_1>Page 1</a>
<a href=index.php?p=page_2>Page 2</a>
<a href=index.php?p=page_3>Page 3</a>
When clicked they include a page (page_1.inc.php or page_2.inc.php or page_3.inc.php) on my page thanks to this script:
<?php
$pages_dir = 'pages';
if(!empty($_GET['p'])){
$pages = scandir($pages_dir, 0);
unset($pages[0], $pages[1]);
$p = $_GET['p'];
if (in_array($p.'.inc.php', $pages)){
include ($pages_dir.'/'.$p.'.inc.php');
}
else {
echo 'Sorry, could not find the page!';
}
开发者_如何学Go }
else {
include($pages_dir.'/home.inc.php');
}
?>
Period.
I also have an xml file looking like this:<program>
<item>
<date>27/8</date>
<title>Page 1</title>
<info>This is info text</info>
</item>
<item>
<date>3/9</date>
<title>Page 2</title>
<info>This is info text again</info>
</item>
<item>
<date>10/9</date>
<title>Page 3</title>
<info>This just some info</info>
</item>
</program>
This is what I want to achieve:
If I click on the link "Page 1" it will display "This is info text" on the page. If I click on the link "Page 2" it will display "This is info text again" on the page. If I click on the link "Page 3" it will display "This just some info" on the page.Was I clear enough? Is there any solution for this?
You should be able to do this with SimpleXMLElement using the xpath() method.
$xmlString = file_get_contents("path/to/xml/file.xml");
$xml = new SimpleXMLElement($xmlString);
$info = $xml->xpath("/program/item[title='Page " . $page . "']/info");
echo (string) $info[0];
Update:
To get an array of all dates you would do something like this:
$xmlString = file_get_contents("path/to/xml/file.xml");
$xml = new SimpleXMLElement($xmlString);
$results = $xml->xpath("/program/item/date");
$dates = array();
if (!empty($results)) {
foreach ($results as $date) {
array_push($dates, (string) $date); // It's important to typecast from SimpleXMLElement to string here
}
}
Also, you could combine the logic, if needed, from the first and second examples. You can reuse the $xml
object for multiple XPath queries.
If you need $dates
to be unique, you can either add an in_array()
check before doing the array_push()
or you can use array_unique()
after the foreach.
精彩评论