如何使用PHP将HTML转换为JSON?

2022-08-30 19:53:09

我可以使用JsontoHtml库将JSON转换为HTML。现在,我需要将当前的HTML转换为JSON,如本网站所示。在查看代码时,我发现了以下脚本:

<script>
$(function(){

    //HTML to JSON
    $('#btn-render-json').click(function() {

        //Set html output
        $('#html-output').html( $('#html-input').val() );

        //Process to JSON and format it for consumption
        $('#html-json').html( FormatJSON(toTransform($('#html-output').children())) );
    });

});

//Convert obj or array to transform
function toTransform(obj) {

    var json;

    if( obj.length > 1 )
    {
        json = [];

        for(var i = 0; i < obj.length; i++)
            json[json.length++] = ObjToTransform(obj[i]);
    } else
        json = ObjToTransform(obj);

    return(json);
}

//Convert obj to transform
function ObjToTransform(obj)
{
    //Get the DOM element
    var el = $(obj).get(0);

    //Add the tag element
    var json = {'tag':el.nodeName.toLowerCase()};

    for (var attr, i=0, attrs=el.attributes, l=attrs.length; i<l; i++){
        attr = attrs[i];
        json[attr.nodeName] = attr.value;
    }

    var children = $(obj).children();

    if( children.length > 0 ) json['children'] = [];
    else json['html'] = $(obj).text();

    //Add the children
    for(var c = 0; c < children.length; c++)
        json['children'][json['children'].length++] = toTransform(children[c]);

    return(json);
}

//Format JSON (with indents)
function FormatJSON(oData, sIndent) {
    if (arguments.length < 2) {
        var sIndent = "";
    }
    var sIndentStyle = "  ";
    var sDataType = RealTypeOf(oData);

    // open object
    if (sDataType == "array") {
        if (oData.length == 0) {
            return "[]";
        }
        var sHTML = "[";
    } else {
        var iCount = 0;
        $.each(oData, function() {
            iCount++;
            return;
        });
        if (iCount == 0) { // object is empty
            return "{}";
        }
        var sHTML = "{";
    }

    // loop through items
    var iCount = 0;
    $.each(oData, function(sKey, vValue) {
        if (iCount > 0) {
            sHTML += ",";
        }
        if (sDataType == "array") {
            sHTML += ("\n" + sIndent + sIndentStyle);
        } else {
            sHTML += ("\"" + sKey + "\"" + ":");
        }

        // display relevant data type
        switch (RealTypeOf(vValue)) {
            case "array":
            case "object":
                sHTML += FormatJSON(vValue, (sIndent + sIndentStyle));
                break;
            case "boolean":
            case "number":
                sHTML += vValue.toString();
                break;
            case "null":
                sHTML += "null";
                break;
            case "string":
                sHTML += ("\"" + vValue + "\"");
                break;
            default:
                sHTML += ("TYPEOF: " + typeof(vValue));
        }

        // loop
        iCount++;
    });

    // close object
    if (sDataType == "array") {
        sHTML += ("\n" + sIndent + "]");
    } else {
        sHTML += ("}");
    }

    // return
    return sHTML;
}

//Get the type of the obj (can replace by jquery type)
function RealTypeOf(v) {
  if (typeof(v) == "object") {
    if (v === null) return "null";
    if (v.constructor == (new Array).constructor) return "array";
    if (v.constructor == (new Date).constructor) return "date";
    if (v.constructor == (new RegExp).constructor) return "regex";
    return "object";
  }
  return typeof(v);
}
</script>

enter image description here

现在,我需要在PHP中使用以下函数。我可以获取 HTML 数据。我现在需要的就是将JavaScript函数转换为PHP函数。这可能吗?我的主要疑惑如下:

  • Javascript 函数的主要输入是一个对象。是否可以通过PHP将HTML转换为对象?toTransform()

  • 这个特定的JavaScript中存在的所有函数在PHP中都可用吗?

请建议我的想法。

当我尝试根据给出的答案将脚本标签转换为json时,我收到错误。当我在json2html站点中尝试它时,它显示如下:enter image description here..如何实现相同的解决方案?


答案 1

如果您能够获得表示HTML的对象,那么您只需要以递归方式遍历它并构造所需的数据结构即可。DOMDocument

将 HTML 文档转换为应该像这样简单:DOMDocument

function html_to_obj($html) {
    $dom = new DOMDocument();
    $dom->loadHTML($html);
    return element_to_obj($dom->documentElement);
}

然后,对它进行简单的遍历,给出您描述的结构类型可能如下所示:$dom->documentElement

function element_to_obj($element) {
    $obj = array( "tag" => $element->tagName );
    foreach ($element->attributes as $attribute) {
        $obj[$attribute->name] = $attribute->value;
    }
    foreach ($element->childNodes as $subElement) {
        if ($subElement->nodeType == XML_TEXT_NODE) {
            $obj["html"] = $subElement->wholeText;
        }
        else {
            $obj["children"][] = element_to_obj($subElement);
        }
    }
    return $obj;
}

测试用例

$html = <<<EOF
<!DOCTYPE html>
<html lang="en">
    <head>
        <title> This is a test </title>
    </head>
    <body>
        <h1> Is this working? </h1>  
        <ul>
            <li> Yes </li>
            <li> No </li>
        </ul>
    </body>
</html>

EOF;

header("Content-Type: text/plain");
echo json_encode(html_to_obj($html), JSON_PRETTY_PRINT);

输出

{
    "tag": "html",
    "lang": "en",
    "children": [
        {
            "tag": "head",
            "children": [
                {
                    "tag": "title",
                    "html": " This is a test "
                }
            ]
        },
        {
            "tag": "body",
            "html": "  \n        ",
            "children": [
                {
                    "tag": "h1",
                    "html": " Is this working? "
                },
                {
                    "tag": "ul",
                    "children": [
                        {
                            "tag": "li",
                            "html": " Yes "
                        },
                        {
                            "tag": "li",
                            "html": " No "
                        }
                    ],
                    "html": "\n        "
                }
            ]
        }
    ]
}

对已更新问题的回答

上面提出的解决方案不适用于该元素,因为它不是被解析为 ,而是作为对象进行解析。这是因为 PHP 中的 DOM 扩展基于 libxml2它将 HTML 解析为 HTML 4.0,而在 HTML 4.0 中,的内容是类型而不是 。<script>DOMTextDOMCharacterData<script>CDATA#PCDATA

对于此问题,您有两种解决方案。

  1. 简单但不是很健壮的解决方案是将标志添加到DOMDocument::loadHTML(我实际上并不是100%确定这是否适用于HTML解析器。LIBXML_NOCDATA

  2. 在我看来,更困难但更好的解决方案是在递归之前进行测试时添加附加测试。递归函数将变为:$subElement->nodeType

function element_to_obj($element) {
    echo $element->tagName, "\n";
    $obj = array( "tag" => $element->tagName );
    foreach ($element->attributes as $attribute) {
        $obj[$attribute->name] = $attribute->value;
    }
    foreach ($element->childNodes as $subElement) {
        if ($subElement->nodeType == XML_TEXT_NODE) {
            $obj["html"] = $subElement->wholeText;
        }
        elseif ($subElement->nodeType == XML_CDATA_SECTION_NODE) {
            $obj["html"] = $subElement->data;
        }
        else {
            $obj["children"][] = element_to_obj($subElement);
        }
    }
    return $obj;
}

如果您遇到另一个这种类型的错误,您应该做的第一件事是检查节点的类型,因为存在许多其他可能性,我的简短示例函数没有处理。$subElement

此外,您会注意到必须修复HTML中的错误才能为其构建DOM。这就是为什么即使您没有指定和 a 元素,也会显示它们的原因。您可以通过使用标志来避免这种情况。libxml2<html><head>LIBXML_HTML_NOIMPLIED

带脚本的测试用例

$html = <<<EOF
        <script type="text/javascript">
            alert('hi');
        </script>
EOF;

header("Content-Type: text/plain");
echo json_encode(html_to_obj($html), JSON_PRETTY_PRINT);

输出

{
    "tag": "html",
    "children": [
        {
            "tag": "head",
            "children": [
                {
                    "tag": "script",
                    "type": "text\/javascript",
                    "html": "\n            alert('hi');\n        "
                }
            ]
        }
    ]
}

答案 2

我假设你的html字符串存储在变量中。所以你应该这样做:$html

$dom = new DOMDocument();
$dom->loadHTML($html);

foreach($dom->getElementsByTagName('*') as $el){
    $result[] = ["type" => $el->tagName, "value" => $el->nodeValue];
}

$json = json_encode($result, JSON_UNESCAPED_UNICODE);

注意:此算法不支持父子标签,支持将所有标签作为父元素提取,并在排序队列中解析所有标签。当然,您可以通过研究类功能来实现此功能。DOMDocument