【问题标题】:php simplexml find text of html tag inside xml elementphp simplexml在xml元素中查找html标签的文本
【发布时间】:2012-03-07 17:34:42
【问题描述】:

如何为xml下面<STRONG>标签内的所有内容设置一个php变量:

<SAVED_EXPORT>
    <metatag_description>
    Some text here? The &lt;strong&gt; Cambro High-Impact 12" x 16" Dietary Tray&lt;/strong&gt; is the solution. Comprised of high-impact, ligh
    </metatag_description>
</SAVED_EXPORT>

<?    foreach( $xml as $SAVED_EXPORT ) {

        $header = $SAVED_EXPORT->metadescription;
        echo $header[0];
        } 
?>

我希望它只是吐出:Cambro High-Impact 12" x 16" Dietary Tray 而不是所有的描述

【问题讨论】:

    标签: php xml xpath simplexml


    【解决方案1】:

    尝试添加以下表达式而不是您的回声:

    if (preg_match("/\&lt\;strong\&gt\;(.*?)\&lt\;\/strong\&gt\;/si", $header[0], $match) == true)
    {
        echo $match[1];
    }
    

    【讨论】:

      【解决方案2】:

      使用 strpos 和 substr:

      $string = 'Some text here? The &lt;strong&gt; Cambro High-Impact 12" x 16" Dietary     Tray&lt;/strong&gt; is the solution. Comprised of high-impact, ligh'; 
      
      // Tag to look for
      $tag       = 'strong';
      $start_tag = '&lt;' . $tag . '&gt;';
      $end_tag   = '&lt;/' . $tag . '&gt;';
      
      // Determine position of search pattern <strong>
      $begin = strpos($string, $start_tag);
      // Add the lenght of the tag string:
      $begin += strlen($start_tag);
      // Determine position of search pattern </strong>
      $end   = strpos($string, $end_tag);
      // Calculate length:
      $length = $end - $begin;
      
      // echo the trimmed substring
      echo trim(substr($string, $begin, $length));
      

      【讨论】:

      • 这个例子更加动态,因为它遍历字符串以找到起始位置。但是,它的动态性较低,因为它假定程序员知道字符串的长度。
      • @nodirtyrockstar - 那么,现在更有活力了。感谢您的意见!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-08
      • 2010-12-16
      • 2011-06-30
      • 1970-01-01
      • 2020-12-07
      相关资源
      最近更新 更多