/    Sign up×
Community /Pin to ProfileBookmark

[RESOLVED] PHP Xpath is not working for SVG images.

Here is the SVG file I’m trying to use the XPath on:

[url]http://mrinitialman.com/StandAlones/XML/olde_english.svg[/url]

My PHP is as follows:

[code=php]
function XMLFile($f, $val=true){
$xml = new DOMDocument();
$xml->Load($f);
if($val){$xml->validate();}
return $xml;
}

$alphabet = XMLFile(‘./Alphabets/olde_english.xml’,false);
$getletters = new DOMXPath($alphabet);
$query='(//path)’;
$letters = $getletters->evaluate($query);
echo ‘<!–‘.n.
‘Path Elements: ‘.$alphabet->getElementsByTagName(‘path’)->length.n.
‘Do we have the right file?: ‘.$alphabet->getElementsByTagName(‘title’)->item(0)->firstChild->data.n.
‘Path Elements Found by XPath: ‘.$letters->length.n.
‘–>’.n;
[/code]

The first uses plain DOMDocument methods to count the path elements.
The second makes sure (by checking the title element) that we actually have the right SVG file
The third checks to see how many path elements we’ve found via the XPath method.

The XML comment results in:

[code=html]
<!–
Path Elements: 62
Do we have the right file?: Olde English Font
Path Elements Found by XPath: 0
–>
[/code]

First: Check; 62 path elements found.
Second: Check; that’s the title of the right document.
Third: . . . Um, uncheck.

My ultimate plan is to use XPath to find the elements by ID attribute without having to validate the SVG file.

[/code]

to post a comment
PHP

1 Comments(s)

Copy linkTweet thisAlerts:
@Mr_Initial_ManauthorAug 26.2015 — I found out the issue--you need to register the namespace the XML file is using BEFORE looking for any elements.

I should have had the following:

[code=php]$alphabet = XMLFile('./Alphabets/olde_english.xml',false);
$getletters = new DOMXPath($alphabet);

$getletters->registerNamespace('svg','http://www.w3.org/2000/svg');

$query='//svg:path';
[/code]


Yeah, if the document has an actual XML Namespace (as do SVG and XHTML documents), you need to factor that in, otherwise the document will look for elements with no namespace. Ah, well, lesson learned. :-)
×

Success!

Help @Mr_Initial_Man spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...