简体   繁体   中英

Assign/echo php file output to a php variable

I'm coding a live search for a lyrics upload form. I've created a small script which I'll be making AJAX calls to. It returns artist , album , and song records. The output JSON will be used in JS.

// get_records.php

include_once("connect2db.php");

if (empty($_GET)) {
    $artists = json_encode(mysqli_fetch_all($mysqli->query("SELECT artist from `artists`"), MYSQLI_ASSOC));
    echo $artists;
} else {
    if (isset($_GET["artist"])) {
        $artist = test_input($_GET["artist"]);
        if (isset($_GET["album"])) {
            // ...
            echo $songs;
        } else {
            // ...
            echo $albums;
        }
    }
}

$mysqli->close();

It's pretty simple. Designed for three cases:

  • get_records.php // returns artists
  • get_records.php?artist=XXX // returns albums of XXX
  • get_records.php?artist=XXX&album=YYY // returns songs from the album YYY that belongs to XXX

In the form page, I want artists to be already assinged to a JS variable before any input. I don't want to use AJAX for that. One way I could make it work is like this:

<?php
    echo "var artists = ";
    include("get_records.php");
    echo ";";
?>

but this just seems wrong. Is there a way to do it like this

<?php
    echo "var artists = " . get_output("get_records.php") . ";";
?>

you know, get the output of the php file, not it's content?

You can do this by putting your code inside a function and then call it from the other scripts as per your need.

Main script:

 <?php

// get_records.php

function execute()
{
    // get_records.php

    include_once("connect2db.php");

    if (empty($_GET)) {
        $artists = json_encode(mysqli_fetch_all($mysqli->query("SELECT artist from `artists`"), MYSQLI_ASSOC));
        $response = $artists;
    } else {
        if (isset($_GET["artist"])) {
            $artist = test_input($_GET["artist"]);
            if (isset($_GET["album"])) {
                // ...
                $response = $songs;
            } else {
                // ...
                $response = $albums;
            }
        }
    }

    $mysqli->close();

    return $response;
}

Ajax Script:

<?php
// ajax_script.php

include_once("get_records.php");

echo execute();

Form Script

<?php

// Form File - form_file.php
include_once("get_records.php");

$content = execute();

$response = "<script> var artists = $content ; </script>";

echo $response;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM