函数文档

_oembed_create_xml()

💡 云策文档标注

概述

_oembed_create_xml() 函数用于将给定的数组转换为 XML 字符串,常用于 oEmbed 响应数据的处理。它递归处理数组,支持嵌套结构,并返回 XML 字符串或错误时的 false。

关键要点

  • 函数接受两个参数:必需的数据数组 $data 和可选的 SimpleXMLElement 节点 $node(默认为 null)。
  • 如果 $data 不是数组或为空,函数返回 false。
  • 递归处理数组:对于数组值,创建子节点并递归调用;对于非数组值,使用 esc_html() 转义后添加为子节点。
  • 数字键会被重命名为 'oembed'。
  • 返回值为字符串(成功时)或 false(错误时)。

代码示例

function _oembed_create_xml( $data, $node = null ) {
    if ( ! is_array( $data ) || empty( $data ) ) {
        return false;
    }

    if ( null === $node ) {
        $node = new SimpleXMLElement( '' );
    }

    foreach ( $data as $key => $value ) {
        if ( is_numeric( $key ) ) {
            $key = 'oembed';
        }

        if ( is_array( $value ) ) {
            $item = $node->addChild( $key );
            _oembed_create_xml( $value, $item );
        } else {
            $node->addChild( $key, esc_html( $value ) );
        }
    }

    return $node->asXML();
}

注意事项

  • 函数在 WordPress 4.4.0 版本中引入。
  • 相关函数包括 esc_html() 用于转义 HTML,以及 _oembed_rest_pre_serve_request() 用于 REST API 输出。
  • 定义在 wp-includes/embed.php 文件中。

📄 原文内容

Creates an XML string from a given array.

Parameters

$dataarrayrequired
The original oEmbed response data.
$nodeSimpleXMLElementoptional
XML node to append the result to recursively.

Default:null

Return

string|false XML string on success, false on error.

Source

function _oembed_create_xml( $data, $node = null ) {
	if ( ! is_array( $data ) || empty( $data ) ) {
		return false;
	}

	if ( null === $node ) {
		$node = new SimpleXMLElement( '<oembed></oembed>' );
	}

	foreach ( $data as $key => $value ) {
		if ( is_numeric( $key ) ) {
			$key = 'oembed';
		}

		if ( is_array( $value ) ) {
			$item = $node->addChild( $key );
			_oembed_create_xml( $value, $item );
		} else {
			$node->addChild( $key, esc_html( $value ) );
		}
	}

	return $node->asXML();
}

Changelog

Version Description
4.4.0 Introduced.