在另一个php文件中调用php函数?

在另一个php文件中调用php函数?,php,function,variables,Php,Function,Variables,我需要从另一个文件example.php中的index.php调用一个函数。如果我使用include,它还将获取index.php中的所有html。我只想要函数的结果。有办法吗 $rs = odbc_exec($con, $sql); if (!$rs) { exit("There is an error in the SQL!");

我需要从另一个文件example.php中的index.php调用一个函数。如果我使用include,它还将获取index.php中的所有html。我只想要函数的结果。有办法吗

                        $rs = odbc_exec($con, $sql);
                        if (!$rs) {
                            exit("There is an error in the SQL!");
                        }
                        $data[0] = array('D','CPU_Purchased_ghz');
                        $i = 1;


                        while($row = odbc_fetch_array($rs)) {
                        $data[$i] = array(
                            $row['D'],
                            $row['CPU_Purchased_ghz']
                        );
                        $i++; 
                        }


                    //odbc_close($con); // Closes the connection
                    $json = json_encode($data); // Generates the JSON, saves it in a variable
                    echo $json;
基本上,index.php中的这段代码从查询数据库的文件中获取信息,并用json对其进行编码。我想创建一个函数来回显json,并在一个新文件中调用它,从而只在页面上显示json,而不是回显。创建一个functions.php文件。将函数添加到该文件中,并将该文件包含在example.php文件中

function myFunction() {
    return "It works!";
}
example.php

include('index.php');
echo myFunction();

在调用函数之前包含该文件

见以下示例:

index.php

function myFunction() {
    return "It works!";
}
现在使用include包含index.php,使其内容可在第二个文件中使用:

example.php

include('index.php');
echo myFunction();

我们能拥有这个函数吗?你必须重构代码。没有其他方法。将函数写入第三个文件function.php并将此文件包含在index.php和example.php中如何?我不认为我可以,因为这是从html表单中提供的信息查询数据库的结果,我只是觉得把结果放在一个函数中,然后放在另一个文件中是很容易的。我不能,因为这是从html表单中提供的信息查询数据库的结果。是的,对不起,我会包括它now@Vickie按照这个例子,首先完成你的任务,如果有任何错误,请告诉我。嘿,正如我在问题中所说,使用Include还可以在新文件中返回html表单,我不需要它,我只需要json php输出!html中有什么,你可以在另一个程序中编写html,只在示例程序中调用索引文件。html是接收数据的形式,因此我想我需要将它们放在同一个文件中-请参阅编辑的问题:请提及这两个文件,我们可以轻松理解你的问题。