[英]Check if XML Chain Exists in PHP
因此,我有以下XML鏈:
$xml->assessment->outcomes_processing->outcomes->decvar->attributes()->cutvalue
XML示例在某些XML文件中確實存在$ xml-> assessmentment-> outcomes_processing-> outcomes->...。 但是這里僅存在$ xml-> assessment。
<questestinterop>
<assessment ident="nedolat78356769204914" title="welkom woordenschat 4">
<qtimetadata>
<qtimetadatafield>
<fieldlabel>qmd_assessmenttype</fieldlabel>
<fieldentry>Assessment</fieldentry>
</qtimetadatafield>
</qtimetadata>
<section ident="nedolat78356769204915" title="Woordenschat">
<selection_ordering>
<selection/>
<order order_type="Sequential"/>
</selection_ordering>
<item ident="QTIEDIT:FIB:34932158" title="Oefening 1">
...
</item>
</section>
</assessment>
</questestinterop>
目前,我收到錯誤消息:“試圖獲取非對象的屬性”。 這是邏輯,因為結果結點不存在。
因此,我嘗試使用isset()解決方案,該解決方案顯然也不起作用。
isset($xml->assessment->outcomes_processing->outcomes->decvar->attributes()->cutvalue) ? ... : null
這給了我同樣的錯誤。 由於節點結果不存在,因此他立即向我拋出錯誤。 解決方案可能是使用isset()單獨檢查每個節點,當然還有一個函數,因為否則我有很多檢查要做...
這是我的功能,由於字符串'->'無法作為php代碼處理而無法正常工作:
// xml: xml structure form SimpleXML
// chain: assessment->outcomes_processing->outcomes->decvar->attributes()->cutvalue
function checkIfXMLChainExists($xml, $chain) {
$xmlChain = '';
$i = 0;
$nodes = explode('->', $chain);
$numItems = count($nodes);
// experimenting with eval() to treat '->' as ->; failed to work
$a = '$xml->assessment->outcomes_processing';
$t = eval($a);
echo $t;
print_r($t);
foreach ($nodes as $node) {
$xmlChain .= '->' . $node;
if (isset($xml->$xmlChain)) { // Node exists
if ($i+1 == $numItems) {
return $xml->$xmlChain;
}
} else { // Node does not exists
return 'does not exist';
}
$i++;
}
有沒有人有一些想法,因為我目前沒有任何靈感:(
提前致謝
返回鏈引用的數據;如果不存在,則返回NULL
。
function getDataIfExists () {
// We accept an unknown number of arguments
$args = func_get_args();
if (!count($args)) {
trigger_error('getDataIfExists() expects a minimum of 1 argument', E_USER_WARNING);
return NULL;
}
// The object we are working with
$baseObj = array_shift($args);
// Check it actually is an object
if (!is_object($baseObj)) {
trigger_error('getDataIfExists(): first argument must be an object', E_USER_WARNING);
return NULL;
}
// Loop subsequent arguments, check they are valid and get their value(s)
foreach ($args as $arg) {
$arg = (string) $arg;
if (substr($arg, -2) == '()') { // method
$arg = substr($arg, 0, -2);
if (!method_exists($baseObj, $arg)) return NULL;
$baseObj = $baseObj->$arg();
} else { // property
if (!isset($baseObj->$arg)) return NULL;
$baseObj = $baseObj->$arg;
}
}
// If we get here $baseObj will contain the item referenced by the supplied chain
return $baseObj;
}
// Call it like this:
$subObj = getDataIfExists($xml, 'assessment', 'outcomes_processing', 'outcomes', 'decvar', 'attributes()', 'cutvalue');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.