使用PHP解析XML

3

我正在尝试使用PHP的SimpleXML解析职位信息。之前我只用过JSON,现在在使用解析器时遇到了问题。这是一些示例数据:

<shrs>
    <rq url="http://api.simplyhired.com/a/jobs-api/xml_v2/q-comission">
        <t>Comission Jobs</t>
        <dt>2011-02-18T23:58:38Z</dt>
        <si>0</si>
        <rpd>10</rpd>
        <tr>192</tr>
        <tv>146</tv>
        <em url=""/>
        <h>
            <kw pos="1"/>
        </h>
    </rq>
    <rs>
        <r>
            <jt>Virtual Recruiter (IT) - Comission ...</jt>
            <cn url="">Remedy Intelligent Staffing</cn>
            <src url="http://api.simplyhired.com/a/job-details/view/jobkey-monster91949932/cjp-0/hits-192?aff_id=28700">Monster</src>
            <ty>organic</ty>
            <loc cty="Buffalo" st="NY" postal="14211" county="" region="" country="US">Buffalo, NY</loc>
            <ls>2011-02-04T05:51:17Z</ls>
            <dp>2011-02-04T05:51:17Z</dp>
            <e>
    Seeking a candidate with previous recruiting experience to work as a Virtual Recruiter for a large client in the IT industry.a Responsibilities: Will recruit, screen, interview, and place candidates for many openings throughout the US Will...
    </e>
        </r>
        <r>
            <jt>Virtual Loan Officer (Mortgage) draw vs comission</jt>
            <cn url="">Netbranchology.com</cn>
            <src url="http://api.simplyhired.com/a/job-details/view/jobkey-7114.353281/cjp-2/hits-192?aff_id=28700">netbranchology.com</src>
            <ty>organic</ty>
            <loc cty="Denver" st="CO" postal="80218" county="" region="" country="US">Denver, CO</loc>
            <ls>2011-02-10T11:47:50Z</ls>
            <dp>2011-01-26T11:36:18Z</dp>
            <e>
    Minimize your overhead by becoming a virtual loan officer... Our client, a Texas-based mortgage banker, has just launched an innovative new program that lets you work from anywhere to originate residential mortgage loans. No office is...
    </e>
        </r>
    </rs>
</shrs>

我想要将 <metadata> 标记中的元数据提取出来赋值到变量中,然后循环遍历 <jobs> 下的每个作业结果进行处理。如何用 PHP 实现这一操作?(目前我一直在使用 SimpleXML 函数试着实现)

2个回答

2

节点可以作为对象属性进行访问,属性使用数组表示法。 foreach 可以让你迭代节点。你可以通过将节点强制转换为字符串来获取节点的内容。(因此如果你使用 echo 就是暗示的)

$shrs = simplexml_load_string($xml);

foreach ($shrs->rs->r as $r)
{
    $jobTitle = $r->jt;
    $city = $r->loc['cty'];

    echo "There's an offer for $jobTitle in $city<br />\n";
}

1
尝试使用SimpleXML:http://www.php.net/manual/en/book.simplexml.php 它可以将您的XML解析成一个漂亮的对象。
编辑:以下是如何使用它(假设您的XML存储在变量$xml中):
$xmlObject = new SimpleXMLElement($xml);

// to retrieve "http://api.simplyhired.com/a/jobs-api/xml_v2/q-comission"
$url = $xmlObject->rq['url'];

// to retrieve "Comission Jobs"
$t = $xmlObject->rq->t;
...

希望能有所帮助。


等等,他发布问题时说的是EasyXML。我猜他犯了一个错误然后进行了编辑。 - Cristian Radu
我打错了,应该是Simple而不是Easy,这是我第一次使用这个库。还是谢谢你,Cristian! - MarathonStudios

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