Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Parse new-line and output 1 value per XML attribute WordPress

  • SOLVED

$gtin is a simple string variable that may have only 1 value, or may have multiple values separated by newline characters.

Current Code:
$output.= ' <g:gtin>' . $gtin . '</g:gtin>' . PHP_EOL;

Current Output:
<g:gtin>00748927027884
00748927027877</g:gtin>


Desired Output:
<g:gtin>00748927027884</g:gtin>
<g:gtin>00748927027877</g:gtin>


How can I make this happen?

Answers (2)

2014-04-28

Arnav Joy answers:

try this

<?php

$gtin = @explode('\n',$gtin);

foreach( $gtin as $val )
$output.= ' <g:gtin>' . $val . '</g:gtin>' . PHP_EOL;
?>


EricNeedsHelp comments:

Thanks, that produces still the same output:
<g:gtin>00748927027884
00748927027877</g:gtin>


Which I'm guessing means my new line is not encoded as a '\n', but not sure.

2014-04-28

Bob answers:

try this

$arr = preg_split("/\r\n|\n|\r/", $gtin);
foreach( $arr as $val )
$output.= '<g:gtin>' . $val . '</g:gtin>' . PHP_EOL;

echo $output;


Bob comments:

You can also try this one
It is slightly modified version of Arnav.


<?php
$gtin = @explode("\r\n",$gtin);
foreach( $gtin as $val )
$output.= ' <g:gtin>' . $val . '</g:gtin>' . PHP_EOL;

?>


Bob comments:

if still not work remove "\r" and try again



<?php

$gtin = @explode("\n",$gtin);
foreach( $gtin as $val )
$output.= ' <g:gtin>' . $val . '</g:gtin>' . PHP_EOL;

?>



Notice double quote here. \n should be in double quote not in single quote.


EricNeedsHelp comments:

Thanks, both
$arr = preg_split("/\r\n|\n|\r/", $gtin);

and
$gtin = @explode("\r\n",$gtin);

Worked :-)


Bob comments:

You can even try this also.

$arr = @explode(PHP_EOL,$gtin);
foreach( $arr as $val )
$output.= '<g:gtin>' . $val . '</g:gtin>' . PHP_EOL;


Bob comments:

Happy to hear that it works. Please close this question by voting :)