xpath - php find xml node thanks to isset variable form url -
i have single.php page want load individual post.
to have links in index.php allows load single.php page :
<a href="single.php?blog_no=12">post 12</a> <a href="single.php?blog_no=11">post 11</a> <a href="single.php?blog_no=10">post 10</a>
i variable in url in single.php page , want find (and display), in xml file, element correspond variable:
<?php if(isset($_get["blog_no"])) { $i = $_get["blog_no"]; $elements = new simplexmlelement('data.xml', null, true); $query = $elements->xpath(" /elements/element[@id='$i'] "); foreach($query $element) { echo $elements->element['size']; echo $elements->element['category']; echo $elements->element->title; } ?>
here example of xml file:
<elements> <element id="12" size="square" category="portfolio"> <tag tag="printer printing 3d apple iphone 5 bumper case"></tag> <icon class="icon-picture"></icon> <urlpage url="/contact/contact.html"></urlpage> <urlimage src='./post thumbnail images/01.png'></urlimage> <date date="8 apr"></date> <title>minimal bumper iphone 5 : protect iphone lightwheight , protect full case </title> </element> <element id="11" size="normal" category="portfolio"> <tag tag="printer printing 3d apple iphone 5 case slim"></tag> <icon class="icon-picture"></icon> <urlpage url="/portfolio/11.html"></urlpage> <urlimage src='./post thumbnail images/tape-dribbble.jpg'></urlimage> <date date="21 jan"></date> <title>ultraslim case</title> </element> </elements>
but nothing works.
you quite close it, this:
if (isset($_get['blog_no'])) { $id = $_get['blog_no']; $xml = simplexml_load_string($x); // assume xml in $x $element = $xml->xpath("//element[@id='$id']")[0]; echo "$element[size] - $element[category]<br />$element->title<br />"; } else { echo "no post selected!" }
explanation:
- in xpath,
//element
means select every<element>
@ position in xml - xpath return array,
[0]
select 1st match. syntax work in php >=5.4, if you're below, let me know , i'll post right code. - no need
foreach
, there can 1<element>
selected, becauseid
unique (i guess).
see working: http://codepad.viper-7.com/ly3itl
Comments
Post a Comment