Get data attribute php

Get data attribute php

To access attributes from classes, methods, functions, parameters, properties and class constants, the Reflection API provides the method getAttributes() on each of the corresponding Reflection objects. This method returns an array of ReflectionAttribute instances that can be queried for attribute name, arguments and to instantiate an instance of the represented attribute.

This separation of reflected attribute representation from actual instance increases control of the programmer to handle errors regarding missing attribute classes, mistyped or missing arguments. Only after calling ReflectionAttribute::newInstance() , objects of the attribute class are instantiated and the correct matching of arguments is validated, not earlier.

Example #1 Reading Attributes using Reflection API

#[Attribute]
class MyAttribute
public $value ;

public function __construct ( $value )
$this -> value = $value ;
>
>

#[MyAttribute(value: 1234)]
class Thing
>

function dumpAttributeData ( $reflection ) $attributes = $reflection -> getAttributes ();

foreach ( $attributes as $attribute ) var_dump ( $attribute -> getName ());
var_dump ( $attribute -> getArguments ());
var_dump ( $attribute -> newInstance ());
>
>

dumpAttributeData (new ReflectionClass ( Thing ::class));
/*
string(11) «MyAttribute»
array(1) [«value»]=>
int(1234)
>
object(MyAttribute)#3 (1) [«value»]=>
int(1234)
>
*/

Instead of iterating all attributes on the reflection instance, only those of a particular attribute class can be retrieved by passing the searched attribute class name as argument.

Example #2 Reading Specific Attributes using Reflection API

function dumpMyAttributeData ( $reflection ) $attributes = $reflection -> getAttributes ( MyAttribute ::class);

foreach ( $attributes as $attribute ) var_dump ( $attribute -> getName ());
var_dump ( $attribute -> getArguments ());
var_dump ( $attribute -> newInstance ());
>
>

dumpMyAttributeData (new ReflectionClass ( Thing ::class));

Источник

Можно ли получить значение data атрибутов в переменную php?

Всем привет!
Есть календарь на wordpress который выводится на определенных страницах в виде месяца разбитого по дням в ячейках.

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

Первый этап с вычислением результата я сделал путем передачи data атрибута в js.

$(".Calendar days").mouseover(function() < var trekdays = $("#trekdays").data('date'); var x = new Date(trekdays); var diff = Math.floor((y.getTime() - x.getTime()) / 86400000); $("#trek_excerpt").attr('data-excerpt', diff); >);

Проблема у меня возникает на обратном этапе передачи параметров из js в php

В атрибут data-excerpt результат записывается и обновляется — ок, но мне нужно, чтобы менялась переменная дней на trek_excerpt_day_1, trek_excerpt_day_2 , trek_excerpt_day_3 и т.д.

Можно ли записать значения data атрибутов в переменную php?

Пробовал передавать результат в ajax, но непонятно какой прописывать путь — шаблона страницы? И если таких страниц несколько

А, если в php вот так записываю, то записываются только исходный html элемента

$str = '

Data

'; echo $str; $doc = new DOMDocument(); $d=$doc->loadHtml($str); $a = $doc->getElementById('trek_excerpt'); var_dump($a->getAttribute('data-excerpt'));

Источник

Могу ли я получить значение дата-атрибута через php?

за foreach мы можем «взять» этот ID и представить его в JS как var product_id = $(this).data(«id»);
Можно ли объявить этот ID товара для функций php взяв его из data-id=»» ?

Простой 6 комментариев

slo_nik

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

добавление класса первичное по клику у меня происходит следующим образом

(document).ready(function()< $(".buy-btn").on("click", function()< var product_id = $(this).data("id"); var qty = $(".qty-"+product_id).val(); $.ajax(< type: "POST", url: "/include/add-cart.php", data: (), cache: false, success: function(data) < $("#reload").html(data); >>); $(this).removeClass('buy-btn').addClass('green-btn').text("В корзине"); localStorage.setItem('addClass', 'true'); >); >); 

Затем проверка наличия айдишников в корзине

 "ASC", "ID" => "ASC" ), array( "FUSER_ID" => CSaleBasket::GetBasketUserID(), "LID" => SITE_ID, "PRODUCT_ID" => $arItem[ID], //ID текущего товара "ORDER_ID" => "NULL", "DELAY" => "N" //Исключая отложенные ), false, false, array("PRODUCT_ID") ); while ($arItemsBasket = $dbBasketItems->Fetch()) < $itInBasket = $arItemsBasket['PRODUCT_ID']; >?>  if (localStorage.getItem('addClass') == 'true') else < //Если товара нет (переменная пустая) ?>?>

В деталке такое работает норм потому что там айди товара аррезульт, а здесь мне нужно как то вытащить значение из атрибута как я сделал в js коде

Источник

How to get HTML Tag Attribute Value in PHP?

In this article we will cover on how to implement php get html tag attribute value. Here you will learn how to get html tag attribute value in php. This article goes in detailed on php how to get html tag attribute value. i would like to share with you php regex get html tag attribute value. Here, Creating a basic example of php get custom attribute value from html.

Here, i will give you simple example how to get html tag attribute value in php. so let’s see both code and output as bellow:

$htmlEle = «

This is ItSolutionStuff.com Example 1

This is ItSolutionStuff.com Example 1

«;

$domdoc = new DOMDocument();

$domdoc->loadHTML($htmlEle);

$xpath = new DOMXpath($domdoc);

$query = «//p[@data-name]»;

$entries = $xpath->query($query);

foreach ($entries as $p) echo $p->getAttribute(‘data-name’), PHP_EOL;

>

Hardik Savani

I’m a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.

We are Recommending you

  • How to Upgrade PHP Version from 7.4 to 8 in Ubuntu?
  • PHP Array Get Previous Element from Current Key
  • PHP Explode Every Character into Array Example
  • PHP Remove Element from Array by Value Example
  • PHP Curl Request with Username and Password Example
  • PHP Curl Delete Request Example Code
  • PHP Curl Get Request with Parameters Example
  • How to Upgrade PHP Version from 7.3 to 7.4 in Ubuntu?
  • Laravel Bootstrap Tag System Example Tutorial
  • HTML Tags are not Allowed in Textbox Validation using JQuery
  • How to Get User IP Address in PHP?

Источник

Access html 5 data attribute in php

Solution 1: Either or Solution 2: Try to concat PHP variable with your string Question: I have a form which includes HTML5 data attribute.

Access html 5 data attribute in php

I have a form which includes

 data-user-id HTML5 data attribute. When I submit the form, I want to use the value of data attribute in a php class. How to access this data attribute in php?

Your user ID should be in a separate hidden field, such as:

  Your message input shouldn't have an id of user-id and shouldn't need data-user-id at all.

Data attributes are used by JavaScript. Hidden inputs pass values to PHP that the user doesn’t need to see. Neither are truly hidden to the user.

If you are posting this form directly to a PHP script, you cannot access the data attributes. If you want to be able to do this you’d need to listen for the form submission in Javascript, then on submit grab the data you need and post it to the PHP script to handle it.

Here is some example code (untested!), using jQuery.

$('#form_name').on('submit',function()< var user_id = $('#user-id').attr('data-user-id'); $.post('form_handle.php',<'user_id':user_id,[. ],[. ]>); >); 

Where [. ] is any other form data to be posted to the handler. The handler can then retrieve posted values in the normal way, e.g. $_POST[‘user_id’] .

How to get html data-attribute string from a php variable, Show activity on this post. Try to concat PHP variable with your string $form .= ‘

PHP Get Data Attribute From HTML5

I want to show both news-evt and news-ntc content in my web page. The JS can POST «news-evt, news-ntc», but the PHP cannot process with this result, how can I do? I am new of php and ajax. Thanks!

**id** **category** 0 news-evt 1 news-ntc 
 $(document).ready(function() < $(document).on('click', '#blog-filters li', function()< var last_id = $(this).data("vid"); $.ajax( < url:"load_data.php", method:"POST", data:, dataType:"text", success:function(data) < if(data !== '') < $('.post-item').remove(); $('.btn-load-more').remove(); $('.blog-content-rows').append(data); >else < $('.btn-load-more a').html("No More. "); >>, >); >); >); 

Solved: Simply change $last_id = $_POST[‘last_id’] to $last_id = explode(‘,’,$_POST[‘last_id’]) and then add foreach ($last_id as $item)

New Problem: But there is a Order problem. the Foreach loop output ‘evt’ result first.

You can always use the echo of PHP.

ID: 1
Output: Some_text
ID: 2
Output: Some_other_text
ID: 3
Output: Another_text

Feel free to ask for anything else.

Use data-attribute in javascript to alter elements width, The proper way to pass data from PHP to JavaScript is using a JSON string. PHP:

How can I get data attributes with php?

Currently I am using this code.

$html = file_get_html($url); $file = $html->find('audio'); $data['download'] = $file->attr['data-file']; 

to try and gather the data from here.

My code from above is not working, for some reason.

$url = 'https://somedomain.com/somesite/'; $content = file_get_contents($url); $first_step = explode( ' ' , $first_step[1] ); echo $data['download']; exit; 

May be Something like this will work.

$DOM = new DOMDocument; $DOM->loadHTML($html); $xpath = new DOMXpath($DOM); $items = $xpath->query("//div[contains(@class,'player-init')]"); $mydata = $items->documentElement->getAttribute('data-file'); 

How do you get data attribute of option tag in php, php can’t work on the client side. If you don’t want to use AJAX/ javascript onchange, you need and a submit button. –

How to get html data-attribute string from a php variable

I am constructing an html form in php with javascript and css, the following line of code works fine and displays a textarea with the required prefix:

However I want to include a php variable i.e

This show the textarea with the prefix ‘Message from $foo’. How do I show it with the value of $foo combined into the data-prefix i.e ‘Message from Foo’?

Any advice would be appreciated, thanks.

Источник

Читайте также:  Ul type disc html
Оцените статью