2014-01-23 243 views
2

這不是一個愚蠢的問題。其他人缺少print_r中的屬性。 但我根本無法訪問屬性xlink:href。PHP SimpleXML缺少屬性

這裏就是我已經試過:

 $xml = simplexml_load_string($imageSVG);   
     $image = $xml->g->image; // works 
     $style = $xml->g->image->style; // works 
     $style = $xml->g->image['style']; // works 
     $remoteHref = $xml->g->image['xlink:href']; // doesn't work 
     $remoteHref = $xml->g->image['href']; // doesn't work 
     $remoteHref = $xml->g->image->href; // doesn't work 
     $array= $xml->g->image->attributes('xlink'); // 0 elements in the array 

這裏的輸入XML:

<?xml version="1.0" encoding="UTF-8" standalone="no" ?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="351" height="351" xml:space="preserve"><desc></desc><defs></defs><g transform="translate(145 175) scale(0.4 0.4)"><image xlink:href="http://cdn.katori.com/BfFEEXuBTrii818CNQvN_71344PL.jpg" style="stroke: none; stroke-width: 1; stroke-dasharray: ; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: rgb(0,0,0); opacity: 1;" transform="translate(-300 -300)" width="600" height="600" preserveAspectRatio="none"></image></g></svg> 

謝謝! -matt

+0

這不是傻瓜? [有數百個這樣的血腥](http://stackoverflow.com/search?q=%5Bphp%5D+simplexml+namespace):P(但是,如果你不知道給你的搜索添加'命名空間'可能有點困難)。 – Wrikken

+0

[Simplexml使用命名空間獲取屬性]的可能重複(http://stackoverflow.com/questions/13511217/simplexml-get-attributes-with-a-namespace) – Wrikken

回答

4

attributes方法需要完整的命名空間,而不只是前綴:

$s = '...'; 

$xml = new SimpleXMLElement($s); 

$attributes = $xml->g->image->attributes('http://www.w3.org/1999/xlink'); 
echo $attributes['href']; 

或使用attributes第二個參數( is_prefix - boolean)並僅指定前綴:

$attributes = $xml->g->image->attributes('xlink', true); 

Here it is in action.

+0

是的!謝謝,就是這樣。 – mdundas

0

simplexml_load_string並不認同這一實物很好地工作:的標籤

如果你知道你想要解析XML的格式,你需要一個快速骯髒的黑客可以隨時爲例如像做

$imageSVG=str_replace(array('xlink:'),array('xlink-'),$imageSVG)

$imageSVG=str_replace(array('xlink:'),array(''),$imageSVG);

之前

simplexml_load_string($imageSVG);

希望它爲你工作