【问题标题】:Looping through Array PHP循环遍历数组 PHP
【发布时间】:2011-04-25 13:27:24
【问题描述】:

我正在尝试循环通过 cURL 数组响应来生成 XML 文件。但是,我生成的文件似乎都具有完全相同的内容 - 我不知道这是否是正确的方法或者我是否应该使用数组,但我似乎无法弄清楚并且可以使用一些新鲜的眼睛.基本上,我希望每个$playlist 的内容都在自己的单独文件中。

for ($i=0; $i<=14; $i++) {
    $xml_data = generateXML($i);
    $fileName = "bc_manifest_$i.xml";
    $fileHandle = fopen($fileName, 'wb') or die("can't open file");
    fwrite ($fileHandle, $xml_data);
    fclose($fileHandle);
    //echo $xml_data;
    echo "Successfully created manifest $i<br />";
  }

// The holy grail
function generateXML($i) {
    $xml_code = array($i);
    // Start the beginning of the xml doc and save it to our reoccuring xml_code var
    $xml_code[$i] .= '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
    $xml_code[$i] .= '<publisher-upload-manifest publisher-id="xxxxxxx" preparer="Dave" report-success="TRUE">' . "\n";

    // Set options to send to brightcove
    // @page_size
    $options = array(
                'page_size' => '75',
                'playlist_ids' => "3690598001,3684920001,8193433701",
                'video_fields'     => 'referenceId,creationDate'    
    );

    // URL Encode the options to prepare for cURL send
    $post_str = '';
    foreach($options as $key=>$value) {
        $post_str .= $key.'='.urlencode($value).'&';
    }
    $post_str = substr($post_str, 0, -1);

    // Initiate cURL and send request
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'http://api.brightcove.com/services/library?command=find_playlists_by_ids&token=xxxxxxxxxx&' );
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_str);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $obj = curl_exec($ch);
    curl_close($ch);

    // Decode json response
    $result = json_decode($obj);

    // Get playlists from the items object
    $playlists = $result->{'items'};

    //var_dump($playlists); 

    // For each playlist...
    foreach ($playlists as $playlist){
        foreach ($playlist->{'videos'} as $video){
            // Convert the creation date to something not so robotic..
            $creation_date_ms = $video->creationDate;
            $creation_date_s = $creation_date_ms / 1000;
            $date = date('Ymd',$creation_date_s);
            $time = strtotime($date);
            //echo $time."<br />";

            // and set the reference id for each video.
            $ref_id = $video->referenceId;

            // Phew! Now, let's first check that there is a reference id for the video. If not, no biggie.
            switch ($ref_id) {
                case "":
                    break;
                default:
                    // If so, run the function to create an xml object for that video!
                    if ($time <= strtotime('20100519')) {
                        $xml_code[$i] .= reencode_from_existing_source($ref_id);
                    }
                    break;
            }        
        }
    }
    // Finish him.
    $xml_code[$i] .= '</publisher-upload-manifest>';
    return($xml_code[$i]);
} //endxml


// Creates an xml object for the passed reference id.
function reencode_from_existing_source($ref_id){
   $xml_obj = '<reencode-from-existing-source
   title-refid="' . $ref_id . '"
   encode-to="MP4"
   encode-multiple="TRUE"
   overwrite-images="FALSE" />' . "\n";
   return ($xml_obj);
}

感谢任何可以提供帮助的人!

【问题讨论】:

  • 您总是使用 cURL 发出相同的请求。
  • 如果源代码减少到仍然存在问题的最低限度,问题对社区更有用。

标签: php xml arrays curl multidimensional-array


【解决方案1】:

我会使用 PHP 中内置的 SimpleXML 或 DOM 功能来生成 XML - 它非常健壮,您只需要传入属性名称、值和节点。

关于为什么你每次都得到相同的结果,你每次都发出相同的 CURL 请求,所以你希望得到相同的结果。

【讨论】:

    【解决方案2】:

    这在过去对我有用:http://snipplr.com/view/3491/convert-php-array-to-xml-or-simple-xml-object-if-you-wish/

    该网址上的记录相当完善,但如果您有任何问题,请告诉我。

    $xml = ArrayToXML::toXML($data_array, 'name_of_root_node');
    

    这应该让你开始。对于第二个参数,将其更改为适合您的任何根节点名称。

    编辑:从上面的链接中添加了 ArrayToXML 类的 sn-p 以减轻链接腐烂的影响。

    class ArrayToXML
    {
        /**
         * The main function for converting to an XML document.
         * Pass in a multi dimensional array and this recrusively loops through and builds up an XML document.
         *
         * @param array $data
         * @param string $rootNodeName - what you want the root node to be - defaultsto data.
         * @param SimpleXMLElement $xml - should only be used recursively
         * @return string XML
         */
        public static function toXml($data, $rootNodeName = 'data', $xml=null)
        {
            // turn off compatibility mode as simple xml throws a wobbly if you don't.
            if (ini_get('zend.ze1_compatibility_mode') == 1)
            {
                ini_set ('zend.ze1_compatibility_mode', 0);
            }
    
            if ($xml == null)
            {
                $xml = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><$rootNodeName />");
            }
    
            // loop through the data passed in.
            foreach($data as $key => $value)
            {
                // no numeric keys in our xml please!
                if (is_numeric($key))
                {
                    // make string key...
                    $key = "unknownNode_". (string) $key;
                }
    
                // replace anything not alpha numeric
                $key = preg_replace('/[^a-z]/i', '', $key);
    
                // if there is another array found recrusively call this function
                if (is_array($value))
                {
                    $node = $xml->addChild($key);
                    // recrusive call.
                    ArrayToXML::toXml($value, $rootNodeName, $node);
                }
                else 
                {
                    // add single node.
                                    $value = htmlentities($value);
                    $xml->addChild($key,$value);
                }
    
            }
            // pass back as string. or simple xml object if you want!
            return $xml->asXML();
        }
    }
    

    【讨论】:

    • 此处的文档(*)表明,没有上下文,仅链接是不好的。虽然我承认我的答案可能不是最好的,但我不觉得它违反了任何规则或约定(没有什么说你不能链接到外部资源——这种情况经常发生)。想澄清一下吗?
    • 问题是链接失效。您永远不知道该链接在一年左右后是否仍然有效。
    • 非常有效的观点!我已经更新了答案以包含有问题的代码。