HTML-теги типа ввода не удаляются PHP Simple HTML DOM Parser

Чтобы удалить html-теги типа ввода с помощью PHP Simple HTML DOM Parser, я попытался сделать следующее:

// Get DOM from URL or file

$html=new simple_html_dom();

// Loads the file from URL

$html->load_file($sourceurl);

// Remove input type text tag

    foreach ($html->find('input[type="text"]') as $e) {

        $e->outertext = '';
    }

Мне также известна эта ссылка здесь: Простой HTML-дом: как удалить элементы?

Но это не работает. Есть ли другой способ/обходной путь?

РЕДАКТИРОВАТЬ: Как и просили, вот полный исходный код:

// Gets the url of the website to be parsed

$sourceurl=$_GET('task');

// Get DOM from URL or file

$html=new simple_html_dom();

// Loads the file from URL

$html->load_file($sourceurl);

// Remove input type text tag

    foreach ($html->find('input[type="text"]') as $e) {

        $e->outertext = '';
    }
echo $html;

person leodeep    schedule 06.11.2013    source источник
comment
Публикация реальной ссылки может помочь найти то, что не так...   -  person Enissay    schedule 06.11.2013
comment
Также ваша функция поиска находит что-нибудь? [напечатайте что-то вроде $index, чтобы быть уверенным, что вы в курсе]   -  person Enissay    schedule 06.11.2013
comment
@Enissay Я вставил настоящую ссылку, отформатировал ее stackoverflow. Обратите внимание на стили форматирования. Да, функция find является встроенной функцией Simple HTML DOM Parser, она находит много вещей. Однако не работает для кода, указанного выше.   -  person leodeep    schedule 06.11.2013
comment
Я говорю о $sourceurl что это?, а также я знаю, что такое find(), я спрашиваю, находит ли он что-то или ничего не возвращает   -  person Enissay    schedule 06.11.2013
comment
$sourceurl – это входной URL-адрес с другой страницы. У него есть данные. $html, вывод, правильно анализирует html и показывает измененный вывод, когда echoed. Однако он не соблюдал некоторые правила. Код, упомянутый выше, является одним из тех немногих правил.   -  person leodeep    schedule 07.11.2013
comment
Опять же, мне нужен исходный код веб-сайта или его URL-адрес, чтобы я мог протестировать его сам...   -  person Enissay    schedule 07.11.2013


Ответы (2)


Код выше должен работать. Вы пытались вывести переменную $html после удаления тегов?

echo (string) $html; // Should print the html content without input tags
person Nauphal    schedule 06.11.2013
comment
Да, у меня есть echo $html; в моем коде, вывод анализирует текстовые поля как есть, не удаляет их. - person leodeep; 06.11.2013

Я не знаком с simple_html_dom(), но если вы можете использовать DOM, вы можете использовать мои занятия. Это всего лишь снимок, но он должен дать вам то, что вам нужно.

Вы также можете увидеть это здесь: http://sandbox.onlinephpfunctions.com/code/aa54bdbf416ae1726ef7ca675b2324c37626920b

Вот класс myDOMDocument()

/**
* myDOMDocument
* 
* This class extend the DOMDocument class with some helpful methods.
* 
* @subpackage DOMDocument
* @version $Revision: 9497 $ $Date: 2007-12-19 17:03:25 +1000 (Tr, 19 Grd 2007) $ $Author: talisin $
* 
*/
class myDOMDocument extends DOMDocument {

    /**
    * Load HTML with mb_convert_encoding before load UTF-8 page
    * to ensure that the output is the same as the input
    *
    * @link http://www.php.net/manual/en/domdocument.loadhtml.php#74777
    * @see DOMDocument::loadHTML()
    * 
    * @param string $html
    * @param string $encoding
    * 
    */
    public function loadHTML($html, $encoding = "UTF-8") {
        $html = mb_convert_encoding($html, 'HTML-ENTITIES', $encoding);
        @parent::loadHTML($html); #suppress warnings
    }

    /**
     * Return HTML while stripping the auto-added tags html, body, and doctype.
     * 
     * @see DOMDocument::saveHTML()
     * @since PHP/5.3.6
     * 
     * @param bool $ignoreAutoAddTags (optional) strip the auto-added tags
     * 
     */
    public function saveHTML( $ignoreAutoAddTags = false ) {
        if( $ignoreAutoAddTags ) {
            $content = preg_replace(array("/^\<\!DOCTYPE.*?<html><body>/si","!</body></html>$!si"),"",parent::saveHTML());
            return $content;
        }
        return parent::saveHTML( parent::documentElement );
    }       

    /**
     * Delete a HTML tag by either a matching tag or additional by tag and his attributes
     * 
     * @example $dom->deleteHtmlTag( 'input', array( 'type' => 'text' ) );
     * This will delete all input type="text" 
     * 
     * 
     * @param string $tag_name Name of the HTML tag to delete
     * @param array $attributes Array of attributes where the key = attribute name and value = attribute value
     */
    public function deleteHtmlTag( $tag_name, $attributes = array() ) {

        $remove_tag = array(); # holds the DOMNodes we want to delete

        foreach (parent::getElementsByTagName($tag_name) as $tag) {

            // if method call has attributes
            if (count($attributes) > 0) {

                // for each HTML attribute of the given node
                foreach ($tag->attributes as $tag_attribute) {

                    // for each given attribute
                    foreach( $attributes as $name => $value ) {
                        if ($tag_attribute->name == $name && $tag_attribute->value == $value ) {
                            $remove_tag[] = $tag;
                        }
                    }

                }

            }

            // otherwise delte the whole tag
            else {
                 $remove_tag[] = $tag;
            }
        }

        if ( count( $remove_tag ) > 0 ) {
            foreach ($remove_tag as $tag) {
                $tag->parentNode->removeChild($tag); 
            } 
        }

    }

}

echo $html = '<div id="hello">Hello</div><input type="text" name="Sample1"><div id="world"><input type="submit" name="Sample2"></div>'.PHP_EOL.PHP_EOL;

$dom = new myDOMDocument();
$dom->loadHTML( $html );
$dom->deleteHtmlTag( 'input', array( 'type' => 'text' ) );
echo $dom->saveHTML( true );
person Talisin    schedule 06.11.2013