Php html dom innertext

Document Object Model

// same as pq(‘anything’)->htmlOuter()
// but on document root (returns doctype etc)
print phpQuery :: getDocument ();
?>

It uses DOM extension and XPath so it works only in PHP5.

If you want to use DOMDocument in your PHPUnit Tests drive on Symfony Controller (testing form)! Use like :

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use YourBundle\Controller\TextController;

class DefaultControllerTest extends WebTestCase
public function testIndex()
$client = static::createClient(array(), array());

$crawler = $client->request(‘GET’, ‘/text/add’);
$this->assertTrue($crawler->filter(«form»)->count() > 0, «Text form exist !»);

$domDocument = new \DOMDocument;

$domInput = $domDocument->createElement(‘input’);
$dom = $domDocument->appendChild($domInput);
$dom->setAttribute(‘slug’, ‘bloc’);

$formInput = new \Symfony\Component\DomCrawler\Field\InputFormField($domInput);
$form->set($formInput);

if ($client->getResponse()->isRedirect())
$crawler = $client->followRedirect(false);
>

// $this->assertTrue($client->getResponse()->isSuccessful());
//$this->assertEquals(200, $client->getResponse()->getStatusCode(),
// «Unexpected HTTP status code for GET /backoffice/login»);

When I tried to parse my XHTML Strict files with DOM extension, it couldn’t understand xhtml entities (like ©). I found post about it here (14-Jul-2005 09:05) which adviced to add resolveExternals = true, but it was very slow. There was some small note about xml catalogs but without any glue. Here it is:

XML catalogs is something like cache. Download all needed dtd’s to /etc/xml, edit file /etc/xml/catalog and add this line:

I hate DOM model !
so I wrote dom2array simple function (simple for use):

function dom2array($node) $res = array();
print $node->nodeType.’
‘;
if($node->nodeType == XML_TEXT_NODE) $res = $node->nodeValue;
>
else if($node->hasAttributes()) $attributes = $node->attributes;
if(!is_null($attributes)) $res[‘@attributes’] = array();
foreach ($attributes as $index=>$attr) $res[‘@attributes’][$attr->name] = $attr->value;
>
>
>
if($node->hasChildNodes()) $children = $node->childNodes;
for($i=0;$ilength;$i++) $child = $children->item($i);
$res[$child->nodeName] = dom2array($child);
>
>
>
return $res;
>

The project I’m currently working on uses XPaths to dynamically navigate through chunks of an XML file. I couldn’t find any PHP code on the net that would build the XPath to a node for me, so I wrote my own function. Turns out it wasn’t as hard as I thought it might be (yay recursion), though it does entail using some PHP shenanigans.

Hopefully it’ll save someone else the trouble of reinventing this wheel.

function getNodeXPath ( $node ) // REMEMBER THAT XPATHS USE BASE-1 INSTEAD OF BASE-0.

// Get the index for the current node by looping through the siblings.
$parentNode = $node -> parentNode ;
if( $parentNode != null ) $nodeIndex = 0 ;
do $testNode = $parentNode -> childNodes -> item ( $nodeIndex );
$nodeName = $testNode -> nodeName ;
$nodeIndex ++;

// PHP trickery! Here we create a counter based on the node
// name of the test node to use in the XPath.
if( !isset( $ $nodeName ) ) $ $nodeName = 1 ;
else $ $nodeName ++;

// Failsafe return value.
if( $nodeIndex > $parentNode -> childNodes -> length ) return( «/» );
> while( ! $node -> isSameNode ( $testNode ) );

// Recursively get the XPath for the parent.
return( getNodeXPath ( $parentNode ) . «/ < $node ->nodeName > [ ]» );
> else // Hit the root node! Note that the slash is added when
// building the XPath, so we return just an empty string.
return( «» );
>
>
?>

If you want to print the DOM XML file content, you can use the next code:

$doc = new DOMDocument();
$doc->load($xmlFileName);
echo «
» . $doc->documentURI;
$x = $doc->documentElement;
getNodeContent($x->childNodes, 0);

function getNodeContent($nodes, $level) foreach ($nodes AS $item) // print «

TIPO: » . $item->nodeType ;
printValues($item, $level);
if ($item->nodeType == 1) < //DOMElement
foreach ($item->attributes AS $itemAtt) printValues($itemAtt, $level+3);
>
if($item->childNodes || $item->childNodes->lenth > 0) getNodeContent($item->childNodes, $level+5);
>
>
>
>

function printValues($item, $level) if ($item->nodeType == 1) < //DOMElement
printLevel($level);
print $item->nodeName . »
«;
if ($level == 0) print «
«;
>
for($i=0; $i < $level; $i++) print "-";
>
>

As of PHP 5.1, libxml options may be set using constants rather than the use of proprietary DomDocument properties.

DomDocument->resolveExternals is equivilant to setting
LIBXML_DTDLOAD
LIBXML_DTDATTR

DomDocument->validateOnParse is equivilant to setting
LIBXML_DTDLOAD
LIBXML_DTDVALID

PHP 5.1 users are encouraged to use the new constants.

Источник

Html innertext substring dom html code example

Solution 1: I dont love this solution, but it works: The regex splits into opening tag, innerText, closing tag. If you assign HTML to an element using the InnerHtml property, InnerText will return all of the text in that HTML with the markup removed.

How can I get a DOMElement’s innerText in PHP?

You should iterate over all elements in the DomDocument and get the text item by item and insert the whitespaces manually. Have a look here for example. DomDocument itself can not know where it should but the whitespaces.

I wrote the following function to recursively traverse the DOMDocument object:

function get_text_from_dom($node, $text) < if (!is_null($node->childNodes)) < foreach ($node->childNodes as $node) < $text = get_text_from_dom($node, $text); >> else < return $text . $node->textContent . ' '; > return $text; > 

And replaced the code in the question with the following:

$doc = new DOMDocument(); $doc->loadHTML($row['body_html']); var_dump(get_text_from_dom($doc->documentElement)); 

InnertTxt html Code Example, Get code examples like «innertTxt html» instantly right from your google search results with the Grepper Chrome Extension.

Replacing some innerTexts in a HTML string with span class and publishing back to DOM

I dont love this solution, but it works:

'Randomz ImageRandomz is the name of the image' .match(/<[^>]+>|[^]+>/g) .map(function (text, index) < if (index === 1) < return text.replace(/(Randomz)/, 'else < return text; >>) .join(''); 

The regex splits into opening tag, innerText, closing tag. Then iterates on all members, if its the innerText, it replaces with desired text Then joins.

Im stil trying to think of something less round-about but thats all i got

Use some form of templating:

String.prototype.template = String.prototype.template || function () < var args = Array.prototype.slice.call(arguments) ,str = this ; function replacer(a)< var aa = Number(a.substr(1))-1; return args[aa]; >return str.replace(/(\$\d+)/gm,replacer); >; var thestring = [ '

This is a sample dataa

Randomz Image$1Randomz$2 ' ,'is the name of the image'].join('') ,nwString = theString.template('

XSS - is it dangerous that innerText string can be HTML elements: script, div etc?

What you're seeing in the elements/DOM tab is misleading you a bit. If you've used innerText (or more appropriately textContent , usually) to set the text of an element, it doesn't have tags in it. It has characters. Those characters can form tags from a display perspective, but they aren't tags and the browser doesn't treat them that way.

One way to see this is to see the HTML for them:

const target = document.getElementById("target"); target.textContent = `alert("Hi!"); 
click me
`; console.log("textContent:", target.textContent); console.log("innerHTML:", target.innerHTML);
 Notice that the element doesn't contain a script tag, it contains the characters < , s , c , r , i , p , t , etc.

In contrast , using innerHTML leaves you wide open to XSS attacks:

const target = document.getElementById("target"); target.innerHTML = `alert("Hi!"); 
click me
`; console.log("textContent:", target.textContent); console.log("innerHTML:", target.innerHTML);
 script tags inserted that way don't get run, but attribute-defined event handlers do, such as the error event on an img that has no src — and the code that that runs could add a script that would get executed:
const target = document.getElementById("target"); target.innerHTML = `
click me
`; console.log("textContent:", target.textContent); console.log("innerHTML:", target.innerHTML);

HtmlElement.InnerText Property

Definition

Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

Gets or sets the text assigned to the element.

public: property System::String ^ InnerText < System::String ^ get(); void set(System::String ^ value); >;
member this.InnerText : string with get, set
Public Property InnerText As String
Property Value

The element's text, absent any HTML markup. If the element contains child elements, only the text in those child elements will be preserved.

Exceptions

The specified element cannot contain text (for example, an IMG element).

Examples

The following code creates a new hyperlink using CreateElement, and assigns text to the link using the InnerText property.

private void AddUrlToTooltip(string url) < if (webBrowser1.Document != null) < HtmlElement elem = webBrowser1.Document.CreateElement("A"); elem.SetAttribute("HREF", url); elem.InnerText = "Visit our Web site for more details."; webBrowser1.Document.Body.AppendChild(elem); >> 
Private Sub AddLinkToPage(ByVal url As String) If (WebBrowser1.Document IsNot Nothing) Then With WebBrowser1.Document Dim Elem As HtmlElement = .CreateElement("A") Elem.SetAttribute("HREF", url) Elem.InnerText = "Visit our web site for more details." .Body.AppendChild(Elem) End With End If End Sub 

Remarks

If you attempt to assign HTML to an element with InnerText, the HTML code will display as literals in the document, just as if you were viewing HTML within a text file. If you assign HTML to an element using the InnerHtml property, InnerText will return all of the text in that HTML with the markup removed.

Assigning a value to InnerText will destroy any child elements that belong to the element.

Applies to

See also

Change innertext dom Code Example, “change innertext dom” Code Answer. change innertext javascript . javascript by TC5550 on Jun 06 2020 Comment . 2. Add a Grepper Answer . Javascript answers related to “change innertext dom” set text of dom element; javascript replace text within dom inner text in html;

Источник

Учимся парсить сайты с библиотекой PHP Simple HTML DOM Parser

Те, кто хоть раз писал парсер, знает, что не стоит этого делать с помощью регулярных выражений. Проиллюстрировать это утверждение поможет следующий пример.

К примеру, из него нам нужно получить описание и url сайта. Если брать исключительно этот кусок кода, то все решается достаточно просто:

echo 'url:' . $list [1]. ',title:' . $list [2]. $list [3]; // выведет url:http://xdan.ru,title:Сайт по программированию парсеров и многое другое

Проблемы начинаются тогда, когда описание сайта заполняют пользователи, и оно не имеет определенного шаблона.

Такой код регулярному выражению не по зубам.

Обычно, в вузах на этот случай учат писать конечный автомат. Суть его в том, что мы перебираем, посимвольно, весь html текст, находим начало тега, и строим дерево документа. Так называемое DOM (Document Object Model)

Сейчас, писать такое самому нет необходимости.

В php, начиная с версии 5, есть встроенные методы работы с деревом документа (класс DOMDocument), но основан он на XML парсере.

А HTML и XML это хоть и очень похожие, но в тоже время абсолютно разные технологии.

К примеру, непременное требование к XML это закрытые теги и отсутствие ошибок.

Отсюда вытекает условие: ошибок в html, который мы парсим с помощью нативных средств php, быть не должно.

К сожалению, на сайтах донорах, ошибки не редки, а значит этот метод отпадает.

Для корректного разбора таких сайтов, на помощь придут php библиотеки PHPQuery, Simple HTML DOM, Zend DOM Query, Nokogiri .

Некоторые из них, после небольших манипуляций скармливают html тому же DOMDocument. Мы не будем их рассматривать.

В этой статье я расскажу про SimpleHTMLDOM. Этой библиотекой я пользуюсь уже несколько лет, и она меня еще ни разу не подводила.

Скачиваем последнюю версию здесь.

Пусть Вас не смущает то, что она не обновлялась с 2008 года, то, что она умеет, полностью покроет Ваши нужды в разборе html текстов.

В архиве, который вы скачали, две папки (примеры работы и документация) и файл simple_html_dom.php.

simple_html_dom.php это и есть вся библиотека, больше ничего для работы не потребуется. Кидаем этот файл в папку с проектом и в своем скрипте просто подгружаем его.

Кроме документации, которую вы скачали с архивом, доступна еще online версия, ее вы найдете здесь

Файл подключен и готов к работе.

Для того, чтобы начать разбирать HTML, его сперва нужно получить. Обычно, я делаю это при помощи библиотеки CURL.

В simplehtmldom есть методы для удаленной загрузки страниц. После подключения файла библиотеки, нам доступны 2 функции для обработки HTML строк.

str_get_htm(str) и file_get_html(url)

Они делают одно и тоже, преобразуют HTML текст в DOM дерево, различаются лишь источники.

str_get_htm – на вход получает обычную строку, т.е. если вы получили HTML прибегнув к curl, или file_get_contents то вы просто передаете полученный текст этой функции.

file_get_html – сама умеет загружать данные с удаленного URL или из локального файла

Источник

Читайте также:  Программа java программирование телефонов
Оцените статью