0
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...

2
Contributors
2
Replies
27
Views
2 Years
Discussion Span
Last Post by Vivek_13
1

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!

Edited by cereal

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.