How to Pass Array from Zend Dom Query Results to table

不打扰是莪最后的温柔 提交于 2019-12-11 09:55:03

问题


I am querying a URL for columns YEAR, RATING and I want to insert those two into a database. E.g. YEAR RATING 1992 9.2 2000 9 1999 8 . . . . . . . .

So, I am writing script like:

$url = 'BLA BLA ';
$data = file_get_contents($url);
$dom = new Zend_Dom_Query($data);
$year = $dom->query('.secondaryInfo');
$rating = $dom->query('.ratingColumn');

How to insert both of them in a database???

for ( .... What do I have to write here?)

$parse = new Application_Model_Parse();
$parse->createImdb(array(
'rating' => What do I have to write here?
'year' => What do I have to write here?
));

Any help will be useful.

Thank you


回答1:


As explained at http://framework.zend.com/manual/1.12/en/zend.dom.query.html

Once you have a document, you can use either the query() or queryXpath() methods; each method will return a Zend_Dom_Query_Result object with any matching nodes.

And further

As mentioned previously, Zend_Dom_Query_Result implements both Iterator and Countable, and as such can be used in a foreach() loop as well as with the count() function.

The various Iterator methods will return PHP's native DOMElements in this case, which means you can access the Element's text content via it's nodeValue property.

Assuming there is only one item in the Result object, try

$parse->createImdb(
    array(
        'rating' => $rating->current()->nodeValue
        'year' => $year->current()->nodeValue
    )
);

If you feel uncomfortable working with an Iterator, you can use:

  • iterator_to_array — Copy the iterator into an array

to, well, copy the iterator into an array and then use that instead, e.g.

$rating = iterator_to_array($rating);
$year = iterator_to_array($year);
$parse->createImdb(
    array(
        'rating' => $rating[0]->nodeValue
        'year' => $year[0]->nodeValue
    )
);

If there is multiple results, iterate them together with a MultipleIterator

$ratingsAndYears = new MultipleIterator();
$ratingsAndYears->attachIterator($rating);
$ratingsAndYears->attachIterator($year);

foreach ($ratingsAndYears as $ratingAndYear) {
    $parse = new Application_Model_Parse();
    $parse->createImdb(
        array(
            'rating' => $ratingAndYear[0]->nodeValue
            'year' => $ratingAndYear[1]->nodeValue
        )
    );

On a sidenote, Zend_Dom_Query is just a thin wrapper around PHP's native DOM extension and if you know XPath, you don't really need the W3 Selector querying it offers and can do it all with DOM alone.



来源:https://stackoverflow.com/questions/19787084/how-to-pass-array-from-zend-dom-query-results-to-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!