【问题标题】:Output PHP Parser Script Variables to PHP form via Sessions通过会话将 PHP 解析器脚本变量输出到 PHP 表单
【发布时间】:2026-01-08 15:45:01
【问题描述】:

PHP 新手,请耐心等待...

我正在尝试将此 simpleXml 解析器脚本中的输出变量发送/提供给另一个 PHP 文件,该文件应该将数据发送到 Brightcove 的媒体 API。

发送脚本:

<?php
session_name("FeedParse");
session_start();
$_SESSION['bcName'] = $title;
$_SESSION['shortDescription'] = $description;
$_SESSION['remoteUrl'] = $videoFile;
$html = "";
$url = "http://feeds.nascar.com/feeds/video?command=search_videos&media_delivery=http&custom_fields=adtitle%2cfranchise&page_size=100&sort_by=PUBLISH_DATE:DESC&token=217e0d96-bd4a-4451-88ec-404debfaf425&any=franchise:%20Preview%20Show&any=franchise:%20Weekend%20Top%205&any=franchise:Up%20to%20Speed&any=franchise:Press%20Pass&any=franchise:Sprint%20Cup%20Practice%20Clips&any=franchise:Sprint%20Cup%20Highlights&any=franchise:Sprint%20Cup%20Final%20Laps&any=franchise:Sprint%20Cup%20Victory%20Lane&any=franchise:Sprint%20Cup%20Post%20Race%20Reactions&any=franchise:All%20Access&any=franchise:Nationwide%20Series%20Qualifying%20Clips&any=franchise:Nationwide%20Series%20Highlights&any=franchise:Nationwide%20Series%20Final%20Laps&any=franchise:Nationwide%20Series%20Victory%20Lane&any=franchise:Nationwide%20Series%20Post%20Race%20Reactions&any=franchise:Truck%20Series%20Qualifying%20Clips&any=franchise:Truck%20Series%20Highlights&any=franchise:Truck%20Series%20Final%20Laps&any=franchise:Truck%20Series%20Victory%20Lane&any=franchise:Truck%20Series%20Post%20Race%20Reactions&output=mrss";
$xml = simplexml_load_file($url);
$namespaces = $xml->getNamespaces(true); // get namespaces

for($i = 0; $i < 50; $i++){ // will return the 50 most recent videos 
  $title = $xml->channel->item[$i]->video;
  $link = $xml->channel->item[$i]->link;
  $title = $xml->channel->item[$i]->title;
  $pubDate = $xml->channel->item[$i]->pubDate;
  $description = $xml->channel->item[$i]->description;
  $titleid = $xml->channel->item[$i]->children($namespaces['bc'])->titleid;
  $m_attrs = $xml->channel->item[$i]->children($namespaces['media'])->content[0]->attributes();
  $videoFile = $m_attrs["url"];
  $html .= //"<h3>$title</h3>$description<p>$pubDate<p>$url<p>Video ID: $titleid<p>

print $title;
print $description;
print $videoFile;
// echo $html;/* tutorial for this script is here https://www.youtube.com/watch?v=4ZLZkdiKGE0 */
}
//http://support.brightcove.com/en/video-cloud/docs/media-write-api-php-example-upload-video
?>

接收脚本:

  <?php 
session_start();
$title = $_SESSION['bcName'];
$description = $_SESSION['shortDescription'];
$videoFile = $_SESSION['remoteUrl'];

// Instantiate the Brightcove class
$bc = new Brightcove(
    '//readtoken//', //Read Token BC 
    '//writetoken//' //Write Token BC 
);

// Set the data for the new video DTO using the form values
$metaData = array(
  '$title' => $_POST['bcName'],
  '$description' => $_POST['bcShortDescription'],

);
//changed all the code below to what i think works for remoteUrl and URLs as opposed to actual video files
// Rename the file to its original file name (instead of temp names like "a445ertd3")
$url = $_URL['remoteUrl'];
//rename($url['tmp_name'], '/tmp/' . $url['name']);
//$url = '/tmp/' . $url['name'];

// Send the file to Brightcove
//Actually, this has been changed to send URL to BC, not file
echo $bc->createVideo($url,$metaData);

class Brightcove {
        public $token_read = 'UmILcDyAFKzjtWO90HNzc67X-wLZK_OUEZliwd9b3lZPWosBPgm1AQ..'; //Read Token from USA Today Sports BC
        public $token_write = 'svP0oJ8lx3zVkIrMROb6gEkMW6wlX_CK1MoJxTbIajxdn_ElL8MZVg..'; //Write Token from USA Today Sports BC 
        public $read_url = 'http://api.brightcove.com/services/library?';
        public $write_url = 'http://api.brightcove.com/services/post';

  public function __construct($token_read, $token_write = NULL ) {
    $this->token_read = $token_read;
    $this->token_write = $token_write;
  }

  public function createVideo($url = NULL, $meta) {
    $request = array();
    $post = array();
    $params = array();
    $video = array();

    foreach($meta as $key => $value) {
      $video[$key] = $value;
    }
    $params['token'] = $this->token_write;
    $params['video'] = $video;

    $post['method'] = 'create_video';
    $post['params'] = $params;

    $request['json'] = json_encode($post);

    if($file) {
      $request['file'] = '@' . $file;
    }

    // Utilize CURL library to handle HTTP request
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $this->write_url);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $request);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_VERBOSE, TRUE );
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 300);
    curl_setopt($curl, CURLOPT_TIMEOUT, 300);
    $response = curl_exec($curl);

    curl_close($curl);

    // Responses are transfered in JSON, decode into PHP object
    $json = json_decode($response);

    // Check request error code and re-call createVideo if request
                // returned a 213 error. A 213 error occurs when you have 
                // exceeded your allowed number of concurrent write requests
    if(isset($json->error))  {
      if($json->error->code == 213) {
        return $this->createVideo($url, $meta);
      } else {
        return FALSE;
      }
    } else {
      return $response;
    }
  }
}

?>​

我是否设置了会话以在此处正常工作?关于为什么接收 PHP 脚本没有获取 PHP 提要解析器脚本输出的数据/变量的任何想法?

【问题讨论】:

  • $title$description$videoFile 在发送脚本中来自哪里?以及这些数据是如何从发送文件发送到接收文件的?在我看来,发送文件只是将数据转储到屏幕上,而不是以任何方式实际调用接收文件。
  • @Travesty3 我认为如果两个 PHP 脚本/文件托管在同一台服务器上,您可以使用会话来允许 $title、$description、$videoFile 可用于其他 PHP 脚本/文件。但你是说我确实需要使用 POST 方法?
  • 您在脚本开头的会话中设置它们。然后你不修改它们,而是修改一开始用来设置这些会话变量的局部变量。但这不会修改会话变量,只会修改局部变量。如果您使用$_SESSION['bcName'] = &amp;$title;,这可能会起作用(注意局部变量名称之前的&amp;)。这意味着变量是assigned by reference,并且只要局部变量发生变化,会话变量就会发生变化,但我会避免这种混淆。

标签: php parsing session simplexml session-variables


【解决方案1】:

在您的发送脚本中,您似乎在脚本的开头设置了会话变量,并且您希望它们在本地变量更改时得到更新。以您编写的方式不会发生这种情况。

您可以通过 assigning the variables by reference 在局部变量名称前添加一个 & 符号 (&amp;) 来实现这一点,但在某些情况下这可能会有点棘手,最好跳过这个令人头疼的问题,而只是直接更新会话变量。

但是,另一个问题是您试图将多个值(50,如代码 cmets 所示)存储到标量会话变量中。因此,每次循环迭代时,它都会覆盖以前的值。也许使用数组结构会更好:

<?php
session_name("FeedParse");
session_start();
$_SESSION['videos'] = array(); // initialize a session variable 'videos' to be an array
$url = "http://feeds.nascar.com/feeds/video?command=search_videos&media_delivery=http&custom_fields=adtitle%2cfranchise&page_size=100&sort_by=PUBLISH_DATE:DESC&token=217e0d96-bd4a-4451-88ec-404debfaf425&any=franchise:%20Preview%20Show&any=franchise:%20Weekend%20Top%205&any=franchise:Up%20to%20Speed&any=franchise:Press%20Pass&any=franchise:Sprint%20Cup%20Practice%20Clips&any=franchise:Sprint%20Cup%20Highlights&any=franchise:Sprint%20Cup%20Final%20Laps&any=franchise:Sprint%20Cup%20Victory%20Lane&any=franchise:Sprint%20Cup%20Post%20Race%20Reactions&any=franchise:All%20Access&any=franchise:Nationwide%20Series%20Qualifying%20Clips&any=franchise:Nationwide%20Series%20Highlights&any=franchise:Nationwide%20Series%20Final%20Laps&any=franchise:Nationwide%20Series%20Victory%20Lane&any=franchise:Nationwide%20Series%20Post%20Race%20Reactions&any=franchise:Truck%20Series%20Qualifying%20Clips&any=franchise:Truck%20Series%20Highlights&any=franchise:Truck%20Series%20Final%20Laps&any=franchise:Truck%20Series%20Victory%20Lane&any=franchise:Truck%20Series%20Post%20Race%20Reactions&output=mrss";
$xml = simplexml_load_file($url);
$namespaces = $xml->getNamespaces(true); // get namespaces

for($i = 0; $i < 50; $i++){ // will return the 50 most recent videos 
  $m_attrs = $xml->channel->item[$i]->children($namespaces['media'])->content[0]->attributes();

  // on each loop iteration, create a new array structure with the video info in it and
  // push it onto the 'video' array session variable
  $video = array(
    'bcName' => $xml->channel->item[$i]->video,
    'shortDescription' => $xml->channel->item[$i]->description,
    'remoteUrl' => $m_attrs["url"],
  );
  $_SESSION['videos'][] = $video;
}

然后,在您的接收脚本中,您将循环访问$_SESSION['videos']

<?php 
session_start();

// Instantiate the Brightcove class
$bc = new Brightcove(
    'UmILcDyAFKzjtWO90HNzc67X-wLZK_OUEZliwd9b3lZPWosBPgm1AQ..', //Read Token from USA Today Sports BC 
    'svP0oJ8lx3zVkIrMROb6gEkMW6wlX_CK1MoJxTbIajxdn_ElL8MZVg..' //Write Token from USA Today Sports BC 

foreach ((array)$_SESSION['videos'] as $video) {
    $title = $video['bcName'];
    $description = $video['shortDescription'];
    $videoFile = $video['remoteUrl'];
    // The code below this line may need to be adjusted. It does not seem quite right.
    // Are you actually sending anything to this script via POST? Or should those just
    // be the values we set above?
    // What is $_URL? Should that just be the $videoFile value?


    // Set the data for the new video DTO using the form values
    $metaData = array(
      '$title' => $_POST['bcName'],
      '$description' => $_POST['bcShortDescription'],

    );
    //changed all the code below to what i think works for remoteUrl and URLs as opposed to actual video files
    // Rename the file to its original file name (instead of temp names like "a445ertd3")
    $url = $_URL['remoteUrl'];
    //rename($url['tmp_name'], '/tmp/' . $url['name']);
    //$url = '/tmp/' . $url['name'];

    // Send the file to Brightcove
    //Actually, this has been changed to send URL to BC, not file
    echo $bc->createVideo($url,$metaData);
}

重要提示:

请注意,这将为会话中的每个视频调用一次 API(听起来每次最多 50 个)。因此,您将在每次运行此脚本时发出 50 个 cURL 请求。这似乎有点沉重,但也许这是意料之中的。如果他们的 API 允许您将数据编译到一个调用中并一次发送所有数据,而不是连接、发送数据、解析响应和断开连接,这将是值得研究的 50 次。

【讨论】:

  • 哇!我不能感谢你在这里的所有反馈,真的很感激!我将立即深入研究您的建议,但有人认为您所说的引起了我的注意:Brightcove API 确实允许您传递一个完整的 JSON 请求,其中包含数据,它看起来像是在接收脚本的末尾(我发布的第二个脚本)它正在传递 JSON,您是否认为有一种方法可以将我的解析器脚本中的 JSON 提要直接提交到将 JSON 直接传递给 Brightcove API 的第二个脚本中的这部分代码?
  • 我尝试使用您建议的更改运行解析器脚本,它给了我一个:致命错误:未捕获的异常 'Exception' 并在 [no active file]:0 堆栈跟踪:#0 {main} 在第 0 行的 [no active file] 中抛出
  • 看起来有一种方法可以使用它们的“buildJSONRequest”函数将数据发送到 Brightcove API,该函数从表单输入中获取数据并创建在 create_video 方法中传递的 JSON-RPC 对象。 API documentation