PHP SimpleXML错误信息

3
Warning:  main() [function.main]: Node no longer exists

我正在通过simplexml_load_file加载一个ml文件,有时它会有一个属性的值,有时则没有。

用法:

$value = $xml->Name->arttributes();

Echo $value; 

如何在没有警告的情况下检查值是否存在错误。

谢谢

4个回答

5

attributes()方法没有返回值吗?这似乎是$xml->Name没有设置。请检查是否设置了$xml->Name:

if( isset($xml->Name) )
      $value = $xml->Name->attributes();

4

在使用节点的任何方法之前,您必须检查该节点是否存在,例如:

if (isset($xml->Name))
{
    $value = $xml->Name->attributes();
}

啊,你打败了我!我赞同这个答案。 - ryanday

0
<?php
$xmlstr = <<<XML
<?xml version='1.0' standalone='yes'?>
<movies>
 <movie>
  <title>PHP: Behind the Parser</title>
  <characters>
   <character>
    <name>Ms. Coder</name>
    <actor>Onlivia Actora</actor>
   </character>
   <character>
    <name>Mr. Coder</name>
    <actor>El Act&#211;r</actor>
   </character>
  </characters>
  <plot>
   So, this language. It's like, a programming language. Or is it a
   scripting language? All is revealed in this thrilling horror spoof
   of a documentary.
  </plot>
  <great-lines>
   <line>PHP solves all my web problems</line>
  </great-lines>
  <rating type="thumbs">7</rating>
  <rating type="stars">5</rating>
 </movie>
</movies>
XML;
?>

<?php
include 'example.php';

$xml = new SimpleXMLElement($xmlstr);

/* Access the <rating> nodes of the first movie.
 * Output the rating scale, too. */
foreach ($xml->movie[0]->rating as $rating) {
    switch((string) $rating['type']) { // Get attributes as element indices
    case 'thumbs':
        echo $rating, ' thumbs up';
        break;
    case 'stars':
        echo $rating, ' stars';
        break;
    }
}
?> 

到目前为止,我们只涵盖了读取元素名称及其值的工作。SimpleXML 还可以访问元素属性。访问元素的属性就像访问数组元素一样简单。

0

我认为正在做:

$attributeValue = isset($xml->attributes()->attributeName) ? $xml->attributes()->attributeName : null;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接