-3

こんにちは、PHP でコードを作成しようとするのはこれが初めてで、長い時間がかかりましたが、データを xml に変換できます。今、JSON オブジェクトを作成する必要がありますが、うまくいきません。最大の問題は、PHP で新しいクラスを作成しようとすることです (私が行ったことが正しいかどうかはわかりません)。これがリストを添付する正しい方法であるかどうか。いくつかは良いと思いますが、私は Java と C# しか使用していないので、少しクレイジーに思えます。私は何か間違ったことをしていると思います。エラーが表示されている行は$array['data']->attach( new Cake($name,$ingredients,$prepare,$image));、しかし、何が間違っているのかわかりません。配列を含めてjsonに変換する行をまだ書いていません

ありがとう

//opens the file, if it doesn't exist, it creates
$pointer = fopen($file, "w");

// writes into json


$cake_list['data'] = new SplObjectStorage();
for ($i = 0; $i < $row; $i++) {

    // Takes the SQL data
    $name = mysql_result($sql, $i, "B.nome");
    $ingredients = mysql_result($sql, $i, "B.ingredientes");
    $prepare = mysql_result($sql, $i, "B.preparo");
    $image = mysql_result($sql, $i, "B.imagem");

    // assembles the xml tags
    // $content = "{";

    // $content .= "}";

    $array['data']->attach( new Cake($name,$ingredients,$prepare,$image));
    // $content .= ",";
    // Writes in file
    // echo $content;
    $content = json_encode($content);

    fwrite($pointer, $content);
    // echo $content;
} // close FOR

echo cake_list;

// close the file
fclose($pointer);

// message
// echo "The file <b> ".$file."</b> was created successfully !";
// closes IF($row)

class Cake {
    var $name;
    var $ingredients;
    var $prepare;
    var $image;

    public function __construct($name, $ingredients, $prepare, $image)
    {
        $this->name = $name;
        $this->ingredients = $ingredients;
    $this->prepare = $prepare;
    $this->image = $image;
    }
}

function create_instance($class, $arg1, $arg2, $arg3, $arg4)
{
    $reflection_class = new ReflectionClass($class);
    return $reflection_class->newInstanceArgs($arg1, $arg2,$arg3, $arg4);
}
4

1 に答える 1

0

$array['data']発生しているエラーは、意図したとおりに実行しているためです$cake_list['data']。エラー行を次のように変更します。

$cake_list['data']->attach(new Cake($name, $ingredients, $prepare, $image));

また、JSON オブジェクト (より正確には JSON オブジェクトの文字列表現) を簡単に作成するには、次のようにします。

$array = array(
    'name' => $name,
    'ingredients' => $ingredients,
    'prepare' => $prepare,
    'image' => $image
);

$json = json_encode($array);

次のような単純で使いやすいオブジェクトを作成することもできます。

$myObject = new stdClass(); // stdClass() is generic class in PHP

$myObject->name        = $name;
$myObject->ingredients = $ingredients;
$myObject->prepare     = $prepare;
$myObject->image       = $image;
于 2013-06-21T04:58:52.350 に答える