1

I'm trying to use PHP with SimpleXML to parse an XHTML file, however the file contains < and > signs which are not part of the markup and cause parsing to fail (opening and end tag mismatches).

How can I convert these to HTML entities before parsing without changing the file or affecting the markup?

Example:

<p> a < b </p>

Would become:

<p> a &lt; <b> </p>
3
  • you should consider to use php.net/manual/en/domdocument.loadhtmlfile.php Commented Feb 15, 2011 at 7:52
  • 2
    Its generally bad practice to use a xml parser on a xhtml document, as its a rare sight that a page actually is valid xhtml. What is the purpose of wanting to parse the page via xml? Commented Feb 15, 2011 at 7:52
  • I want to parse a table of products from an xhtml page and store them in a database and wasn't aware of the DOMDocument::loadHTMLFile, however it seems to choke on < as well :( Commented Feb 15, 2011 at 8:05

2 Answers 2

2

Well the short answer is: you can't parse html with regex.

Maybe you could try using another xml parser that doesnt' choke on the < and > ?

Better yet, don't try to parse an xhtml file as xml, since as you already point out yourself, it isn't really an xml file, and has illegal characters in it.

Sign up to request clarification or add additional context in comments.

Comments

1

As Martin Jespersen already said, there is no good way to parse (invalid or valid) markup with regexes, at least not with PHP regexes.

That said, if you're only looking for a way to remove

  • unbalanced angle brackets
  • that are between valid tags
  • which do not contain angle brackets somewhere inside their attribute values

then you might get away with doing this:

$intermediate = preg_replace('/(>[^<>]*)<([^<>]*<)/', '\1&lt;\2', $subject);
$result = preg_replace('/(>[^<>]*)>([^<>]*<)/', '\1&gt;\2', $intermediate);

but you'd have to run this several times until there are no more matches because this will only catch one stray < or > between tags at a time. It will also fail on pseudo-balanced brackets like <p> a <> b </p>.

1 Comment

Got away with your suggestion and using DOMDocument::loadHTMLFile instead of SimpleXML and it works a treat, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.