首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用PHP SimpleXml解析XML文档的故障排除

使用PHP SimpleXml解析XML文档的故障排除
EN

Stack Overflow用户
提问于 2011-12-14 07:30:16
回答 1查看 210关注 0票数 0

我以前使用过xpath来处理XML元素,但是我一直在努力为这个特定的XML找到正确的语法。

我正在尝试解析守护应用程序接口响应。回复示例:

代码语言:javascript
运行
复制
<response user-tier="approved" current-page="1" start-index="1" page-size="10" pages="1" total="10" status="ok">
<results>
<tag type="series" web-title="Cycling" section-name="Life and style"   id="lifeandstyle/series/cycling" api-   url="http://content.guardianapis.com/lifeandstyle/series/cycling" section-id="lifeandstyle" web-  url="http://www.guardian.co.uk/lifeandstyle/series/cycling"/>
 <tag type="keyword" web-title="Cycling" section-name="Sport" id="sport/cycling" api- url="http://content.guardianapis.com/sport/cycling" section-id="sport" web- url="http://www.guardian.co.uk/sport/cycling"/>
 <tag type="keyword" web-title="Cycling" section-name="Life and style"   id="lifeandstyle/cycling" api-url="http://content.guardianapis.com/lifeandstyle/cycling"    section-id="lifeandstyle" web-url="http://www.guardian.co.uk/lifeandstyle/cycling"/>
 <results>
 <response>

这是我第一次尝试用PHP编写代码(我是用cURL连接的):

代码语言:javascript
运行
复制
 $news_items = new SimpleXMLElement($result); //loads the result of the cURL into a simpleXML response 

 $news_items = $guardian_response->xpath('results'); 

 foreach ($news_items as $item) { //for each statement every entry will load the news_item  and the web_url for the document
    $item_block = "<p class=\"web_title\">";
$item_block = "<p class=\"web_url\">";
  }

它不能检索任何东西,我的代码中有什么缺陷吗?

EN

回答 1

Stack Overflow用户

发布于 2011-12-14 23:38:51

代码语言:javascript
运行
复制
<?php
    function getAttribute($object, $attribute) { 
        foreach($object->attributes() as $a => $b) { 
            if ($a == $attribute) { $return = $b; } 
        } 
        if($return) { return $return; } 
    } 

    try {
        $xml = simplexml_load_file( "parse.xml" );

        /* Pay attention to the XPath, include all parents */
        $result = $xml->xpath('/response/results/tag');

        while(list( , $node) = each($result)) {
             echo getAttribute( $node, "type" );
        }

    } catch( Exception $e ) {
        echo "Exception on line ".$e->getLine()." of file ".$e->getFile()." : ".$e->getMessage()."<br/>";
    }
?>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8497732

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档