Html php содержимое элемента

DOMDocument php, как получить содержимое блока, с html тегами?

а именно необходимо получить содержимое блока с идентификатором «firstElement», вместе с HTML тегами. Я использую DOMDocument, но получается вывести только текст.

Подскажите пожалуйста, как правильно получить содержимое?

P.S. вложенных блоков может быть сколько угодно много! и у всех может быть разное содержание!

deleted-tnorman

Вот чудо методы для работы с дом-моделью в PHP.
Я не сильно понял вопрос, но благодаря всякой фигне, которая тут написана, мне удалось управлять DOM моделью в PHP.

Вам надо обратить внимание на всякие такие штуки как DOMElement. Потому, что получив DOMDocument веселье не кончается. Теперь вам надо наладить работу с его «Документа» элементами. А значит не помешает так же распочковать структуру всех искомых элементов.
Это можно делать с помощью методов работы с ДОМЕлементами. Такими методами как

public DOMNodeList getElementsByTagName ( string $name )

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

После публикации вопроса, прошло время и вот что я добился!
Перекурил документацию по php, и сделал вот так:

$file = file_get_contents('../test.html'); libxml_use_internal_errors(TRUE); $node = new DOMDocument(); $text = $node->loadHTML('' . $file); $id = $node->getElementById('firstElement'); $html = $node->saveHTML($id);

Тут я добился, что переменная $html — представляет собой ‘string’ со всем содержимым тут все понятно.

Но дальше необходимо вставить $html в другой документ в блок с известным идентификатором, рабочее решение будет с использованием регулярки (написана прям тут) таким:

$file = file_get_contents('./какой-тоФайл.html'); preg_replace('/(\)/', '\\1 $html', $file);

А вот используя DOMDocument и все такое, я не могу вставить узел, не могу понять (или еще не дочитал) как! Причем пытаюсь использовать DOMNode::appendChild и передаю ей $id из кода выше, но не работает!

Источник

How to Get HTML Tag Value in PHP | DOMDocument Object

Inside this article we will see the concept i.e How to get HTML tag value in PHP. If you are looking of an article which makes you understand about How to parse HTML tags and elements then this article is best to get those concept.

DOMDocument object of PHP used to parse HTML string value. If we want to get tag name, it’s values etc then object will help for all those.

DOMDocument of PHP also termed as PHP DOM Parser. We will see step by step concept to get the HTML tag value using DOM parser.

Example 1: PHP Get HTML Element Value

Create a file index.php at your localhost directory. Open index.php and write this complete code into it.

This is Sample Text Message 1

This is Sample Text Message 2

This is Sample Text Message 3

"; // DOM Parser Object $htmlDom = new DOMDocument(); $htmlDom->loadHTML($htmlElement); $paragraphTags = $htmlDom->getElementsByTagName('p'); foreach ($paragraphTags as $paragraph) < echo $paragraph->nodeValue . "
"; >

Here, we are getting all paragraph tags by Tag “P”

$paragraphTags = $htmlDom->getElementsByTagName('p');

When we run index.php. Here is the output

This is Sample Text Message 1 This is Sample Text Message 2 This is Sample Text Message 3

Example 2: PHP Get HTML Element Value By ID

Let’s assume the given string value for this example. Open index.php and write this complete code into it.

"; // DOM Parser Object $htmlDom = new DOMDocument(); $htmlDom->loadHTML($htmlString); $paragraphTagValue = $htmlDom->getElementById('sampleParagraph')->nodeValue; echo $paragraphTagValue;

Here, nodeValue returns value of node by it’s ID.

$htmlDom->getElementById('sampleParagraph')->nodeValue;

When we run index.php. Here is the output

This is a sample text message for Testing…

We hope this article helped you to learn How to Get HTML Tag Value in PHP i.e DOMDocument Object in a very detailed way.

Источник

How can I get a div content in php

Am I correct that the last line in your ‘UPDATED’ code declaring $id should follow with a semicolon for PHP syntax?

3 Answers 3

$dom = new DOMDocument(); $dom->loadHTML($html); $xpath = new DOMXPath($dom); $divContent = $xpath->query('//div[@id="product_list"]'); 

Are any external libraries required to run the code you pasted here? I ask this because the code does not seem to work directly on my server.

No, but requires the libxml PHP extension. php.net/manual/en/dom.requirements.php Check your phpinfo(). Have you got any error message?

This does not retrieve the HTML, it retrieves an object with one property: length . The correct answer is the one provided by stackoverflow.com/users/497139/thw just below. Direct link: not possible on SO for whatever reason.

To save an XML/HTML fragment, you need to save each child node:

$dom = new DOMDocument(); $dom->loadHTML($html); $xpath = new DOMXPath($dom); $result = ''; foreach($xpath->evaluate('//div[@id="product_list"]/node()') as $childNode) < $result .= $dom->saveHtml($childNode); > var_dump($result); 
string(74) " 
bla bla bla
bla bla "

If you only need the text content, you can fetch it directly:

$dom = new DOMDocument(); $dom->loadHTML($html); $xpath = new DOMXPath($dom); var_dump( $xpath->evaluate('string(//div[@id="product_list"])') ); 
string(63) " bla bla bla bla bla " 

Источник

how to extract text from a html element by id and assign to a php variable?

and I want to extract the hello word using its id and assign this to a php var but I don’t have an idea. If it were an input it would be easier, but I have to use a different element.

assuming you have just that string, there is strip_tags() which will just leave the hello . But the fact that you want to get that by using it’s id suggests that there are other tags also, so you need to parse the dom

I think we’re a little short on info here. If you are trying to get a value from your page you can use javascript to grab the value from a div, put it into a hidden input, and then submit a form with that hidden input, and pick it up in your php code on the server. But you also might have a cms with a bunch of html in one column and you’re trying to parse it and grab values out. What are you doin?

3 Answers 3

Ok, Rene Limon, as you already know, PHP variables exist on the server side, while the text «hello» exists on the client side. So, what you need is to send the value («hello» or any other) to the server. It’s possible to do it with Ajax. Next file (sendhello.php) gets the value inside the tag and send it to the server. The second file (sendhelloo.php) gets the value and stores it in a variable. To test my code you have to create two text files with the given names, copy-paste the code in them, open your browser and type «localhost/sendhello.php» :

sendhello.php

      

hellooo


sendhelloo.php

)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f3.0%2f" data-se-share-sheet-license-name="CC BY-SA 3.0" data-s-popover-placement="bottom-start">Share
)" title="">Improve this answer
answered Jun 11, 2015 at 18:07
1
    When I tested this on my local machine, the XMLHttpRequest was blocked because of the cross origin policy. But it worked fine once pushed to the web server. Thanks!
    – thingEvery
    Jan 30, 2019 at 22:19
Add a comment|
0
else < echo ""; > ?>

Источник

Читайте также:  Первая страница на php
Оцените статью