Search code examples
xpathsimplexmlphpisset

php find xml node thanks to isset variable form url


I have a single.php page where I want to load individual post.

To do this I have some links in my index.php that allows to 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 get the variable in the url in my single.php page and I want to find (and display), in a xml file, the element that correspond to this 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 as $element) {

    echo $elements->element['size'];
    echo $elements->element['category'];
    echo $elements->element->title;

}
?>

Here an example of my 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 for iPhone 5 : Protect your iphone with a lightwheight and 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.


Solution

  • You were quite close to it, do it like 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:

    1. in xpath, //element means to select every <element> at any position in the XML
    2. xpath will always return an array, the [0] will select only the 1st match. This syntax will work in PHP >=5.4, if you're below, let me know and I'll post the right code.
    3. No need for foreach, there can only be one <element> selected, because the id is unique (I guess).

    See it working: http://codepad.viper-7.com/LY3itL