Microsoft.WebApplication.targets не был найден на сервере сборки. Какое у тебя решение?

Если вы можете получить объект DOMDocument, представляющий ваш HTML-код, вам просто нужно пройти его рекурсивно и построить структуру данных, которую вы хотите.

Преобразование 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 = <<

    
         This is a test 
    
    
        

Is this working?

  • Yes
  • No
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        "
                }
            ]
        }
    ]
}

Ответ на обновленный вопрос

Решение, предложенное выше, не работает с элементом 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        "
                }
            ]
        }
    ]
}

390
задан stacker 21 October 2010 в 17:04
поделиться