Api partly working

Been working on this for a few days got it partly working, Please help
This api is to capture NAV of mutual funds. On the website it is working correctly and showing all data
as
" {“meta”:{“fund_house”:“PPFAS Mutual Fund”,“scheme_type”:“360 ONE Mutual Fund”,“scheme_category”:“Formerly Known as IIFL Mutual Fund”,“scheme_code”:122639,“scheme_name”:“Parag Parikh Flexi Cap Fund - Direct Plan - Growth”},“data”:[{“date”:“15-05-2024”,“nav”:“77.69770”}],“status”:“SUCCESS”}"

This api code is working partly it is capturing the name of the fund correctly but not the nav

<?php
$fundCodes = array('122639/latest');

foreach ($fundCodes as $fundCode) {
    $url = 'https://api.mfapi.in/mf/' . $fundCode;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    $response = curl_exec($ch);

    
        $data = json_decode($response, true);


            if (array_key_exists('nav', $data['data'])) {
                $nav = $data['data']['nav'];
                echo $nav;
                echo 'Fund: ' . $data['meta']['scheme_name'] ['data']. ' - NAV: ' . $nav . '<br>';
            } else {
                echo 'Error: NAV data not available for ' . $data['meta']['scheme_name'] . '<br>';
            }
        }


    curl_close($ch);

?>

If you examine the decoded data, using echo '<pre>'; print_r($data); echo '</pre>'; you should get something that looks like -

Array
(
    [meta] => Array
        (
            [fund_house] => PPFAS Mutual Fund
            [scheme_type] => 360 ONE Mutual Fund
            [scheme_category] => Formerly Known as IIFL Mutual Fund
            [scheme_code] => 122639
            [scheme_name] => Parag Parikh Flexi Cap Fund - Direct Plan - Growth
        )

    [data] => Array
        (
            [0] => Array
                (
                    [date] => 15-05-2024
                    [nav] => 77.69770
                )

        )

    [status] => SUCCESS
)

The nav value is at $data[‘data’][0][‘nav’]

many thanks :grinning:
I would have never guessed it!

Use this :

<?php
$fundCode = '122639/latest';
$url = 'https://api.mfapi.in/mf/' . $fundCode;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
} else {
    $data = json_decode($response, true);

    if (isset($data['data'][0]['nav'])) {
        $nav = $data['data'][0]['nav'];
        echo 'Fund: ' . $data['meta']['scheme_name'] . ' - NAV: ' . $nav . '<br>';
    } else {
        echo 'Error: NAV data not available for ' . $data['meta']['scheme_name'] . '<br>';
    }
}

curl_close($ch);
?>
Sponsor our Newsletter | Privacy Policy | Terms of Service