【问题标题】:how to add a custom attributes with PHP Simple HTML DOM Parser如何使用 PHP Simple HTML DOM Parser 添加自定义属性
【发布时间】:2014-08-25 20:42:10
【问题描述】:

我正在处理一个需要使用 PHP Simple HTML Dom Parser 的项目,我需要一种方法来根据类名向多个元素添加自定义属性。

我可以使用 foreach 循环遍历元素,并且设置标准属性(如 href)很容易,但我找不到添加自定义属性的方法。

我能猜到的最接近的是:

foreach($html -> find(".myelems") as $element) {
     $element->myattr="customvalue";
}

但这不起作用。

我已经看到了许多关于类似主题的其他问题,但他们都建议使用另一种方法来解析 html(domDocument 等)。在我的情况下,这不是一个选项,因为我必须使用 Simple HTML DOM Parser。

【问题讨论】:

    标签: php html simple-html-dom


    【解决方案1】:

    好吧,我认为它太旧了,但我仍然认为它会帮助像我这样的人:)

    所以在我的例子中,我将自定义属性添加到图像标签中

    $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');
    }
    

    【讨论】:

      【解决方案2】:

      你试过了吗?试试这个例子(示例:添加数据标签)。

      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);
      

      输出:

      <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>
      

      【讨论】:

      • 嗯,它将标签转换为实体。就像它将

        转换为 <p>

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-21
      • 2019-09-21
      • 2014-09-04
      • 1970-01-01
      相关资源
      最近更新 更多