how to add a custom attributes with PHP Simple HTML DOM Parser

前端 未结 2 1701
醉话见心
醉话见心 2021-01-22 16:43

I am working with a project that require the use of PHP Simple HTML Dom Parser, and I need a way to add a custom attribute to a number of elements based on class name.

I

相关标签:
2条回答
  • 2021-01-22 16:49

    Did you try it? Try this example (Sample: adding data tags).

    include 'simple_html_dom.php';
    
    $html_string = '
    <style>.myelems{color:green}</style>
    <div>
        <p class="myelems">text inside 1</p>
        <p class="myelems">text inside 2</p>
        <p class="myelems">text inside 3</p>
        <p>simple text 1</p>
        <p>simple text 2</p>
    </div>
    ';
    
    $html = str_get_html($html_string);
    foreach($html->find('div p[class="myelems"]') as $key => $p_tags) {
        $p_tags->{'data-index'} = $key;
    }
    
    echo htmlentities($html);
    

    Output:

    <style>.myelems{color:green}</style> 
    <div> 
        <p class="myelems" data-index="0">text inside 1</p> 
        <p class="myelems" data-index="1">text inside 2</p> 
        <p class="myelems" data-index="2">text inside 3</p> 
        <p>simple text 1</p> 
        <p>simple text 2</p> 
    </div>
    
    0 讨论(0)
  • 2021-01-22 17:13

    Well, I think it's too old post but still i think it will help somebody like me :)

    So in my case I added custom attribute to an image tag

    $markup = file_get_contents('pathtohtmlfile');
    
    //Create a new DOM document
    $dom = new DOMDocument;
    
    //Parse the HTML. The @ is used to suppress any parsing errors
    //that will be thrown if the $html string isn't valid XHTML.
    @$dom->loadHTML($markup);
    
    //Get all images tags
    $imgs = $dom->getElementsByTagName('img');
    
    //Iterate over the extracted images
    foreach ($imgs as $img)
    {
        $img->setAttribute('customAttr', 'customAttrVal');
    }
    
    0 讨论(0)
提交回复
热议问题