Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion source/FluidXml/FluidInsertionHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -269,9 +269,15 @@ protected function insertStringSimple($parent, $k, $v, $fn): array
// The user has passed an element name and an element value:
// [ 'element' => 'Element content' ]

$el = $this->createElement($k, $v);
$el = $this->createElement($k);
$el = $fn($parent, $el);

// createTextNode escapes XML special characters (&, <, >, etc.)
// DOMElement's constructor does not, so we avoid passing value there.
if ($v !== null && $v !== '') {
$el->appendChild($this->dom->createTextNode((string) $v));
}

return [ $el ];
}

Expand Down
26 changes: 26 additions & 0 deletions specs/FluidXml.php
Original file line number Diff line number Diff line change
Expand Up @@ -1181,6 +1181,32 @@ function addchild($parent, $i)
assert_equal_xml($xml, $expected);
});

it('should escape XML special characters in text content using the argument syntax', function () {
$xml = new FluidXml();
$xml->addChild('child1', 'a & b')
->addChild('parent', true)
->addChild('child2', 'a < b');

$expected = "<doc>\n"
. " <child1>a &amp; b</child1>\n"
. " <parent>\n"
. " <child2>a &lt; b</child2>\n"
. " </parent>\n"
. "</doc>";
assert_equal_xml($xml, $expected);
});

it('should escape XML special characters in text content using the array syntax', function () {
$xml = new FluidXml();
$xml->addChild(['child1' => 'Hello & World', 'child2' => 'Tom & Jerry']);

$expected = "<doc>\n"
. " <child1>Hello &amp; World</child1>\n"
. " <child2>Tom &amp; Jerry</child2>\n"
. "</doc>";
assert_equal_xml($xml, $expected);
});

it('should add many children with and without a value', function () {
$xml = new FluidXml();
$xml->addChild(['child1', 'child2', 'child3' => 'value3', 'child4' => 'value4'])
Expand Down