function getRandomNode($file, $numOfQue)
{
    $xml = simplexml_load_file($file);


        foreach($xml->main as $main)
        {
            //Here I want to Get Ramdom Node using $numOfQue.
            //$numOfQue is a random node Number
        }

    $xml->asXml($file);
}

guys Help me...

Recommended Answers

All 2 Replies

Hi,

you could count the nodes, create a range array and then shuffle the range, finally you return the node, for example:

<?php 

    $xml = <<<EOD
<?xml version="1.0" encoding="UTF-8"?>
<main>
    <articles>
        <article>
            <title>Title 001</title>
            <content>Content 001</content>
        </article>
        <article>
            <title>Title 002</title>
            <content>Content 002</content>
        </article>
        <article>
            <title>Title 003</title>
            <content>Content 003</content>
        </article>
    </articles>
</main>
EOD;

    $load  = simplexml_load_string($xml);
    $count = $load->articles->article->count();

    if($count > 0)
    {
        $numbr = $count > 2 ? $count - 1 : $count;
        $range = range(0, $numbr);

        shuffle($range);

        echo $load->articles->article[$range[0]]->title . PHP_EOL;
    }

    else
    {
        echo "No articles found!";
    }

If you have doubts, please show your XML structure, otherwise it's difficult to help. Bye!

works perfect ...tnxs

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.