Skip to content

Improve parsing XHTML structure #7

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 7, 2015
Merged
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
24 changes: 21 additions & 3 deletions src/Io/Loader.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,36 @@

class Loader
{
private $entities;

public function __construct(array $entities = null)
{
if ($entities === null) {
// get all HTML entities (minus those for XML parsing)
$entities = get_html_translation_table(HTML_ENTITIES, ENT_NOQUOTES, 'UTF-8');
unset($entities['<'], $entities['>'], $entities['&']);
}

$this->entities = $entities;
}

public function loadXmlFile($path)
{
return $this->loadXmlString(file_get_contents($path));
}

public function loadXmlString($html)
{
// fix invalid markup of help link in footer of outdated ViewVC versions
// fix invalid markup of outdated ViewVC versions
// - help link in footer not terminated
// - selected branch/tag in CVS "sticky tag" dropdown has not attribute value
// - clear button for selected branch/tag has no trailing slash
$html = str_replace('Help</strong></td>', 'Help</a></strong></td>', $html);
$html = str_replace('selected>', 'selected="selected">', $html);
$html = preg_replace('#<input([^\/]+)>#', '<input$1 />', $html);

// replace unneeded HTML entities
$html = str_replace('&nbsp;', ' ', $html);
// replace named HTML entities with their UTF-8 value
$html = str_replace(array_values($this->entities), array_keys($this->entities), $html);

// clean up namespace declaration
$html = str_replace('xmlns="', 'ns="', $html);
Expand Down
25 changes: 25 additions & 0 deletions tests/Io/LoaderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,29 @@ function ($path) {
scandir(__DIR__ . '/../fixtures/')
));
}

public function testHtmlEntities()
{
$str = '<p>&auml;&hellip;&nbsp;&copy;</p>';
$xml = $this->loader->loadXmlString($str);

// c3 a4 e2 80 a6 c2 a0 c2 a9
$this->assertEquals('ä… ©', (string)$xml);
}

public function testLoadInvalidMarkupInputNotClosed()
{
$str = '<input type="hidden">';
$xml = $this->loader->loadXmlString($str);

$this->assertEquals('hidden', (string)$xml['type']);
}

public function testLoadInvalidMarkupSelectedAttributeNoValue()
{
$str = '<option selected>this</option>';
$xml = $this->loader->loadXmlString($str);

$this->assertEquals('selected', (string)$xml['selected']);
}
}