简体   繁体   中英

how to cut tag in string with PHP

I Have a problem with this output receive value.

  $simple="<TRAN_ID>17564_36428.1354_4159</TRAN_ID>
           <TRAN_DATE>20160201</TRAN_DATE>
           <TRAN_TIME>10:07:08</TRAN_TIME>
           <ERROR_CODE>1</ERROR_CODE>
           <ERROR_DESC>Not Input Policy</ERROR_DESC>
           <POLICY_NBR></POLICY_NBR>";

I want to cut the code with PHP.

    TRAN_ID = ?
    TRAND_DATE = ?
    ERROR_CODE = ?
    ERROR_DESC = ?

How can i do it. sorry my english is bad. Thanks.

You can use PHP's SimpleXML library, like so:

<?php
    $str ="<TRANS><TRAN_ID>17564_36428.1354_4159</TRAN_ID><TRAN_DATE>20160201</TRAN_DATE><TRAN_TIME>10:07:08</TRAN_TIME><ERROR_CODE>1</ERROR_CODE><ERROR_DESC>Not Input Policy</ERROR_DESC><POLICY_NBR></POLICY_NBR></TRANS>";

    $transaction = simplexml_load_string($str);

    echo $transaction->TRAN_ID.PHP_EOL;
    echo $transaction->TRAN_DATE.PHP_EOL;
    echo $transaction->TRAN_TIME.PHP_EOL;
    echo $transaction->ERROR_CODE.PHP_EOL;
    echo $transaction->ERROR_DESC.PHP_EOL;
    echo $transaction->POLICY_NBR.PHP_EOL;

Note that I added <TRANS> start and end tags to your string.

If the data always looks like the sample, this should work okay.

<?php
function getTextBetweenTags($string, $tagname) {
    $pattern = "/<$tagname ?.*>(.*)<\/$tagname>/";
    preg_match($pattern, $string, $matches);
    return $matches[1];
}

$str = '<textformat leading="2"><p align="left"><font size="10">get me</font></p></textformat>';
$txt = getTextBetweenTags($str, "font");
echo $txt;
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM