[英]How to get XML content that is “outside” of tag (with PHP's SimpleXMLElement)?
<order>
XXX
<orderValue>YYY</orderValue>
</order>
我無法弄清楚如何獲取純XXX (使用PHP的SimpleXMLElement),因為通過直接標記無法訪問它。 $ order-> orderValue肯定會交付YYY , $ order會交付order-tag中的所有內容。 XML根據codebeautify.org-validator和xmlwf-shell-validator有效。
您不需要定位任何目標,您已經在節點上擁有了想要獲取的值
$xml = simplexml_load_string('
<order>
XXX
<orderValue>YYY</orderValue>
</order>
');
echo $xml;
輸出XXX
您可能必須使用echo (string) $xml;
在某些情況下。
您擁有的XML:
<order>
XXX
<orderValue>YYY</orderValue>
</order>
從技術上講與PHP中的Simplexml 不兼容 。 即使ClémentMalet概述了這個微小的片段在他回答的孤立示例中確實起作用,您還是在這里指的是更普遍的問題,Simplexml與數據訪問不兼容,因此文檔節點的排列更加不同(可能)。 。
不要誤會我的意思,XML是有效的 ,Simplexml將加載它(它也不會破壞文檔)。 但是, SimpleXMLElement的接口無法將您在此處擁有的混合子節點的地址提高到您可能需要的詳細程度:
"XXX"
<orderValue>
Simplexml通過在技術上允許父元素僅具有一種類型的子節點,簡化了對XML文檔中數據的訪問。 因此,僅元素或文本。
對於所有與眾不同的事物,都有一個名為Dom的姐妹圖書館 ,該圖書館可以互換使用。 通過擴展SimpleXMLElement,您甚至可以在此處創建現有代碼的一些擴展,而無需對其進行過多更改。
讓我們向SimpleXMLElement添加一個新方法,該方法返回您感興趣的任何元素的所有子節點(文本節點和元素節點)並命名該方法childNodes :
/**
* Extend SimpleXMLElement to access child-nodes more differentiated.
*
* Demonstration to work together with DOM sister library
*/
class MyXml extends SimpleXMLElement
{
public function childNodes() {
$nodes = [];
foreach(dom_import_simplexml($this)->childNodes as $node) {
if ($node instanceof DOMText) {
$nodes[] = $node->nodeValue;
} elseif ($node instanceof DOMElement) {
$nodes[] = simplexml_import_dom($node);
} // ... other node-types ignored in this example
}
return $nodes;
}
}
根據創建SimpleXMLElement的方式,您可以傳遞一些參數,以告訴您要使用哪個SimpleXMLElement類。 這是我的字符串示例:
$buffer = <<<XML
<doc>
<order>
XXX <!-- XXX is never reachable as-is with pure SimpleXML -->
<orderValue>YYY</orderValue>
ZZZ <!-- same for ZZZ -->
</order>
</doc>
XML;
$xml = simplexml_load_string($buffer, 'MyXml');
我使用simplexml_load_string
函數創建SimpleXMLElement。 它有第二個參數,我可以在其中傳遞要使用的類名。 然后,您可以使用添加的方法:
var_dump($xml->order->childNodes()[0]); // first child-node string(11) "\n XXX "
如您所見,您也許無法使用“純” Simplexml做到這一點,但是您可以擴展接口並從DOM姐妹庫提供的更詳細的訪問中受益。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.